这个执行者有一些已知的问题吗?还是我用错了方法?我需要在单独的线程中安排上传,并且我希望在当前上传完成后的特定时间后触发下一次上传。
因此,我的服务实现中有一些代码摘录:
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 之间获取位置更新,但是位置侦听器在主线程上运行,并且位置更新之间有几秒钟的时间间隔,因此没有什么应该阻止调度的执行器触发......但它迟到了超过预定延误的三倍!这怎么可能?