ScheduledExecutorService 中断具体任务的定期执行

4

我有一堆工作,它们会定期使用ScheduledExecutorService运行。现在我想停止某些任务的周期性执行,而其他任务则不受影响。这个问题应该如何解决?

1个回答

5

ScheduledExecutorService中的方法返回ScheduledFuture。您可以保留对此ScheduledFuture的引用,并在需要取消的特定ScheduledFuture上调用cancel。

也许可以将它们保存在一个带有某种标识符的映射中,以便知道要取消哪些任务。

ScheduledExecutorService bla;    
//Put a bunch of scheduled stuff in a map
for(int i = 0; i < 10; i++){
    map.put(i, bla.schedule(() -> {}, 10, TimeUnit.DAYS));  
}
//Cancel number 5
map.get(5).cancel(true);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接