java中调度可运行任务

发布于 2024-08-19 03:54:14 字数 547 浏览 6 评论 0原文

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

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

这里需要注意的一件事是任务本身与时间表完全解耦——

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

其中——

SomeTask task = new SomeTask();

所以任务本身不知道时间表。请告知是否有办法让任务取消并为自己创建新的计划。

谢谢

I am following up an interesting question on so, on usage of ScheduledThreadPoolExecutor for some repeating task.

Scheduling this object returns a ScheduledFuture object which one can use to cancel the next run of the task.

One thing to note here is the task itself is completely decoupled from the schedule--

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

where-

SomeTask task = new SomeTask();

So the task itself is not aware of the schedule. Please enlighten if there is a way to get the task to cancel and create a new schedule for itself.

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

浅黛梨妆こ 2024-08-26 03:54:14

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

There's no reason why the task cannot reference the ScheduledExecutorService and schedule itself to run again if required:

// (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);
    }
  }
}
美羊羊 2024-08-26 03:54:14

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

SomeTask task = new SomeTask(executor);

Pass the executor to the task, so that it can make manipulations with it:

SomeTask task = new SomeTask(executor);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文