8

我正在跟进一个有趣的问题,关于将 ScheduledThreadPoolExecutor 用于某些重复任务。

调度此对象会返回一个 ScheduledFuture 对象,可以使用该对象取消任务的下一次运行。

这里需要注意的一件事是任务本身与日程完全脱钩——

ScheduledExecutorService executor = new ScheduledThreadPoolExecutor(1);
ScheduledFuture nextSchedule = 
    executor.schedule(task, 60000, TimeUnit.MILLISECONDS);

在哪里-

SomeTask task = new SomeTask();

所以任务本身并不知道时间表。如果有办法让任务取消并为自己创建一个新的计划,请赐教。

谢谢

4

2 回答 2

7

如果需要,任务没有理由不能引用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);
    }
  }
}
于 2010-01-23T22:26:55.753 回答
4

将 传递executor给任务,以便它可以对其进行操作:

SomeTask task = new SomeTask(executor);
于 2010-01-23T22:29:14.627 回答