2013-01-09 11 views
3

這個執行程序是否存在一些已知問題?或者我用錯了方式?我需要在單獨的線程中安排上傳,並且我希望在當前上傳完成後的某段時間後啓動下一個上傳。Executors.newSingleThreadScheduledExecutor()的可靠性日程表

因此,有從我的服務執行一些代碼摘錄:

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之間獲得位置更新,但是位置監聽器在主線程上運行,位置更新之間有幾秒鐘的長週期,因此沒有任何事情應該阻止預定的執行程序啓動......但它遲到超過預定延遲的三倍!那可能怎麼樣?

+0

如果您正在調度,那麼至少應該使用AlarmManager。通常服務可能會停在中間,如果Cpu處於睡眠模式,調度程序將不會喚醒CPU,但是alarmManager將會 – nandeesh

+0

令我驚訝的是,第二個可運行的程序在啓動前不等待3分鐘 – fiddler

+0

@fiddler 300000ms是五分鐘,正如你在前三次比賽開始5分鐘後的前三分鐘日誌中看到的一樣 –

回答

1

您需要使用AlarmManager而不是執行程序/處理程序或使用部分Wakelock來保持cpu處於開啓狀態。

如果cpu處於睡眠模式,您的應用程序將不會運行,直到手機被喚醒。
AFAIK只有AlarmManager可以通過喚醒設備來給你回電。爲此,您需要使用ELAPSED_REALTIME_WAKEUPRTC_WAKEUP類型,其他選項將再次導致延遲。