2010-02-16 123 views
9

我有一個計劃任務(在固定延遲執行中運行),開始是這樣的:什麼是重新啓動ScheduledExecutorService計劃任務的正確方法?

executoreService.scheduleWithFixedDelay(repeatingThread, 0, numOfSeconds, TimeUnit.SECONDS); 

在週期的每一個開始,我爲您在設置文件的改變,然後我要重新啓動的任務。設置文件還包含間隔的長度(上述代碼中的numOfSeconds)。

目前,我使用下面的代碼來重新啓動任務:

executoreService.shutdownNow(); 
try { 
while(!executoreService.awaitTermination(5, TimeUnit.SECONDS)){ 
    logger.debug("awaiting termintation"); 
} 
} catch (InterruptedException e) { 
logger.debug("interrupted, continuing", e); 
} 
// initialize startup parameters 
init(); 
// start the main scheduled timer 
executoreService.scheduleWithFixedDelay(repeatingThread, 0, numOfSeconds, TimeUnit.SECONDS); 

我不知道這些API調用。推薦重新啓動任務的方式是什麼(可能會有新的延遲)?

回答

13

不,您不希望或需要關閉整個服務只是爲了修改一項任務。請使用從服務中獲得的ScheduledFuture對象取消該任務,然後安排一個新的任務。

ScheduledFuture<?> future = executorService.scheduleWithFixedDelay(repeatingThread, 0, numOfSeconds, TimeUnit.SECONDS); 
... 
// to cancel it: 
future.cancel(true); 
// then schedule again 

另外,爲什麼不更新狀態在任何repeatThread與新的設置或參數?如果你不需要新的延遲,它甚至不需要重新安排。

+0

這是一件需要考慮的事情,但它更容易實現將覆蓋設置更改的任何情況。即設置文件中的任何變化*可能*也會改變延遲。因此,不是檢查延遲是否發生了變化,然後做一件事,如果不是那樣的話,那麼我寧願在任何情況下重新啓動。 – Ovesh 2010-02-16 10:32:30

相關問題