Вопрос

Is there some known issue with this executor? Or am I using it wrong way? I need to schedule uploads in separate thread and I want the next upload to fire after a certain time after current upload had finished.

So there are some code excerpts from my Service implementation:

ScheduledExecutorService periodicUploadExecutor;

@Override
public void onCreate() {
    super.onCreate();

    // some stuff...

    periodicUploadExecutor = Executors.newSingleThreadScheduledExecutor();
    periodicUploadExecutor.schedule(uploadPointsToServer, getCurrentUploadIntervalInMs(), TimeUnit.MILLISECONDS);
}

private Runnable uploadPointsToServer = new Runnable() {
    public void run() {

        Log.d("SOMETAG", "--->>>  UPLOAD runnable started!");

        // upload stuff here...

        Log.d("SOMETAG", " upload runnable scheduling next after "+getCurrentUploadIntervalInMs());
        periodicUploadExecutor.schedule(uploadPointsToServer, getCurrentUploadIntervalInMs(), TimeUnit.MILLISECONDS);

        Log.d("SOMETAG", "<<<---  upload runnable ENDED!");
    }
}

private final int getCurrentActiveSampIntervalInMs() {
    return 300000; // just an example
}

But as I examine the logs I see the following:

01-08 15:33:42.166 D/SOMETAG ( 4606): --->>>  UPLOAD runnable started!
01-08 15:33:43.166 D/SOMETAG ( 4606):  upload runnable scheduling next after 300000
01-08 15:33:43.166 D/SOMETAG ( 4606): <<<---  upload runnable ENDED!
01-08 15:38:43.166 D/SOMETAG ( 4606): --->>>  UPLOAD runnable started!
01-08 15:38:44.174 D/SOMETAG ( 4606):  upload runnable scheduling next after 300000
01-08 15:38:44.174 D/SOMETAG ( 4606): <<<---  upload runnable ENDED!
01-08 15:43:44.174 D/SOMETAG ( 4606): --->>>  UPLOAD runnable started!
01-08 15:43:45.143 D/SOMETAG ( 4606):  upload runnable scheduling next after 300000
01-08 15:43:45.143 D/SOMETAG ( 4606): <<<---  upload runnable ENDED!
01-08 16:01:38.887 D/SOMETAG ( 4606): --->>>  UPLOAD runnable started!

So first three go well but the last one starts after eighteen minutes, not five! This service also gets location updates between 15:43 and 16:01, but location listener operates on main thread and there are few seconds long periods between location updates so nothing should block scheduled executor to fire... but it is late by more than three times the scheduled delay! How's that possible?

Это было полезно?

Решение

You need to use AlarmManager instead of Executor/handler or use a Partial Wakelock to keep the cpu on.

If cpu is in sleep mode, your app will not run until phone wakes up.
AFAIK only AlarmManager can get you a callback by waking up the device. For this you need to use either ELAPSED_REALTIME_WAKEUP or RTC_WAKEUP type, other options will again result in delay.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top