![](/img/trans.png)
[英]Retrieving a task instance scheduled with ScheduledExecutorService
[英]What is the correct way to restart a ScheduledExecutorService scheduled task?
我有一個計划任務(在固定延遲執行中運行),像這樣開始:
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調用。 重啟任務的推薦方法是什么(可能有新的延遲)?
不,您不想或不需要關閉整個服務只是為了修改一項任務。 而是使用從服務獲得的ScheduledFuture對象來取消任務,然后安排一個新任務。
ScheduledFuture<?> future = executorService.scheduleWithFixedDelay(repeatingThread, 0, numOfSeconds, TimeUnit.SECONDS);
...
// to cancel it:
future.cancel(true);
// then schedule again
或者,為什么不只是使用新的設置或參數更新repeatThread中的狀態? 如果你不需要新的延遲,它甚至不需要重新安排。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.