[英]scheduling runnable tasks in java
關於使用ScheduledThreadPoolExecutor執行某些重復任務,我正在跟進一個有趣的問題 。
調度此對象將返回ScheduledFuture對象,可以使用該對象取消下一次任務運行。
這里要注意的一件事是任務本身與時間表完全脫鈎 -
ScheduledExecutorService executor = new ScheduledThreadPoolExecutor(1);
ScheduledFuture nextSchedule =
executor.schedule(task, 60000, TimeUnit.MILLISECONDS);
哪里-
SomeTask task = new SomeTask();
所以任務本身並不了解時間表。 如果有辦法讓任務取消並為自己創建一個新的時間表,請啟發。
謝謝
沒有理由為什么任務不能引用ScheduledExecutorService
並安排自己在需要時再次運行:
// (Need to make variable final *if* it is a local (method) variable.)
final ScheduledExecutorService execService = Executors.newSingleThreadScheduledExecutor();
// Create re-usable Callable. In cases where the Callable has state
// we may need to create a new instance each time depending on requirements.
Callable<Void> task = new Callable() {
public Void call() {
try {
doSomeProcessing();
} finally {
// Schedule same task to run again (even if processing fails).
execService.schedule(this, 1, TimeUnit.SECONDS);
}
}
}
將executor
傳遞給任務,以便它可以使用它進行操作:
SomeTask task = new SomeTask(executor);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.