【问题标题】:scheduling runnable tasks in java在java中调度可运行任务
【发布时间】:2011-01-08 15:50:42
【问题描述】:

我正在跟进一个有趣的question,关于使用 ScheduledThreadPoolExecutor 执行某些重复任务。

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

这里需要注意的一点是,任务本身与日程完全解耦--

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

在哪里-

SomeTask task = new SomeTask();

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

谢谢

【问题讨论】:

  • 顺便说一句,通常的做法是至少对您接受的答案进行投票(“这个答案很有用”是投票图标的标题)

标签: java timer scheduling timer-jobs


【解决方案1】:

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

SomeTask task = new SomeTask(executor);

【讨论】:

  • 这应该发生在我身上。谢谢博卓
【解决方案2】:

任务没有理由不能引用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);
    }
  }
}

【讨论】:

    猜你喜欢
    • 2020-03-28
    • 2015-03-20
    • 2014-04-14
    • 2020-11-06
    • 2022-08-04
    • 1970-01-01
    • 1970-01-01
    • 2018-04-16
    • 1970-01-01
    相关资源
    最近更新 更多