java - 在java中调度可运行的任务

标签 java timer scheduling timer-jobs

我正在跟进一个有趣的 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/

相关文章:

java - 为什么我收到 Ja.lang.StackOverflowError

c# - Thread.Sleep 或 Timer 用于显示每一步

timer - 以秒级精度为用户任务计时

java - 如何初始化继承的值,并使用抽象方法c++?

使用有效指针从 C 调用方法后出现 Java JNI NullPointerException

c - Linux 调度 : OS vs "virtual"

algorithm - 系统编程 |调度时间

c - 使用 pthread 模拟循环

java - 设计问题: Static vs Non-static instance variables

delphi - 设置定时器暂停