java中调度可运行任务
我正在跟进一个有趣的问题,关于使用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
任务没有理由无法引用
ScheduledExecutorService
并在需要时安排自身再次运行:There's no reason why the task cannot reference the
ScheduledExecutorService
and schedule itself to run again if required:将
执行器
传递给任务,以便它可以对其进行操作:Pass the
executor
to the task, so that it can make manipulations with it: