这个执行器有什么已知问题吗?还是我用错了?我需要安排上传在单独的线程,我希望在当前上传完成后的特定时间后触发下一次上传。
因此,我的服务实现中有一些代码摘录:
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!
所以前三个很顺利,但最后一个在 18 分钟后开始,而不是 5 分钟!该服务还在 15:43 和 16:01 之间获取位置更新,但是位置监听器在主线程上运行,并且位置更新之间有几秒钟的时间间隔,所以没有什么应该阻止计划的执行程序触发......但它是 延迟时间是原定延迟的三倍多!这怎么可能?
最佳答案
您需要使用 AlarmManager
而不是 Executor/handler 或使用 Partial Wakelock保持CPU开启。
如果 cpu 处于 sleep 模式,您的应用程序将不会运行,直到手机被唤醒。
AFAIK 只有 AlarmManager
可以通过唤醒设备给你一个回调。为此,您需要使用 ELAPSED_REALTIME_WAKEUP
或 RTC_WAKEUP
类型,其他选项将再次导致延迟。
关于android - Executors.newSingleThreadScheduledExecutor().schedule 的可靠性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14236303/