我正在跟进一个有趣的 question因此,关于使用 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);
}
}
}
关于java - 在java中调度可运行的任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2124987/