简体   繁体   中英

Run command every 30 minutes in thread on Android service

I have an Android service running within my app in the background, this service runs several threads, one of which is meant to run a command ever 30 minutes.

Thread InternetThread = new Thread() {
        public void run() {
            while (true){
                    try {
                        Thread.sleep(1800000);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    Log.i("test", "We are running");
                    runCommand();
            }
        }
    };

However what I have found is this code will not always run every 30 minutes, some times it can be up to an hour between runs, never less than 30 minutes but can be more. I assume this has something to do with the service being pursed by Android? But I am not really sure as this is at the limited of my understanding with Android services and threads.

Hopefully someone can help with a way to make sure the "runCommand()" does actually run exactly every 30 minutes.

The process may be freezing, try this:

Thread InternetThread = new Thread() {
    public void run() {
        long endtime = 0;
        while (true) {
            endTime = System.currentTimeMillis() + 1800000;
            while(System.currentTimeMillis() < endTime) {
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            Log.i("test", "We are running");
            runCommand();
            }
        }
    };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM