Executors.newSingleThreadScheduledExecutor()。schedule的可靠性

时间:2013-01-09 13:28:21

标签: android multithreading scheduledexecutorservice

此执行程序是否存在一些已知问题?或者我错误地使用它?我需要在单独的帖子中安排上传,我希望在当前上传完成后的一段时间后启动下一次上传。

所以我的服务实现有一些代码摘录:

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
}

但是当我检查日志时,我看到以下内容:

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!

所以前三个顺利但最后一个在十八分钟后开始,而不是五个!此服务还在15:43和16:01之间获取位置更新,但位置监听器在主线程上运行,并且位置更新之间有几秒钟的长时间,因此没有任何东西可以阻止计划的执行程序触发......但是< / strong>迟到超过预定延迟的三倍!怎么可能?

1 个答案:

答案 0 :(得分:1)

您需要使用AlarmManager而不是Executor / handler或使用Partial Wakelock来保持cpu。

如果cpu处于睡眠模式,则在手机唤醒之前,您的应用才会运行 仅AFAIK AlarmManager可以通过唤醒设备来回复您。为此,您需要使用ELAPSED_REALTIME_WAKEUPRTC_WAKEUP类型,其他选项将再次导致延迟。