简体   繁体   中英

How to start action at a fixed rate on Android?

I have a service in my Android app that has to do some actions once every 5 minutes.

In order to achieve this I've tried to run TimerTask through Timer.scheduleAtFixedRate method, but the rate appeared not to be fixed at all - after some hours of running ticks stop, then (after some hours!) timer wakes up and instantly fires a series of couple of dozens ticks... According to the reference its a normal behaviour:

If an execution is delayed for any reason (such as garbage collection or other background activity), two or more executions will occur in rapid succession to "catch up."

so I had to look for another solution.

Next I've tried ScheduledExecutorService and it's scheduleAtFixedRate method, following the answer from scheduleAtFixedRate executes fast . It also doesn't fully resolve the issue - I observe the same freezes, though they are shorter (up to an hour).

My current code is simple:

    scheduler = Executors.newSingleThreadScheduledExecutor();
    scheduler.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                Log.d(LOG_TAG, "Schedule run");

                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        Log.d(LOG_TAG, "Call timer");

                        serviceHelper.doAction();

                        Log.d(LOG_TAG, "Task complete");
                    }
                });
            }
        }, 0, AppConstant.NOTIFY_INTERVAL, TimeUnit.MILLISECONDS);

So, I need an advice how to add stability to the schedule (a gap of +-3 minutes is acceptable, but 10 to 30 minutes is the way too much).

I have a service in my Android app that has to do some actions once every 5 minutes. In order to achieve this I've tried to run TimerTask [...] Next I've tried ScheduledExecutorService

I think you are using wrong tool for the task as I'd consider AlarmManager far better choice. See docs' Scheduling Repeating Alarms , and make sure you understand the difference between exact and inexact alarms introduced in API 19 (as you definitely do not want the latter).

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