且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使ScheduledExecutorService在其计划任务被取消时自动终止

更新时间:2023-01-12 18:26:19

c> ScheduledThreadPoolExecutor ( Executors.newScheduledThreadPool )返回的实际类型文档:

From the ScheduledThreadPoolExecutor (the actual type returned by Executors.newScheduledThreadPool) documentation:


当提交的任务在运行之前被取消时,执行被禁止。默认情况下,这样取消的任务不会从工作队列中自动删除,直到它的延迟过去。虽然这可以进行进一步的检查和监视,但它也可能导致取消任务的无限保留。要避免这种情况,请将setRemoveOnCancelPolicy(boolean)设置为true,这会导致任务在取消时立即从工作队列中删除。

When a submitted task is cancelled before it is run, execution is suppressed. By default, such a cancelled task is not automatically removed from the work queue until its delay elapses. While this enables further inspection and monitoring, it may also cause unbounded retention of cancelled tasks. To avoid this, set setRemoveOnCancelPolicy(boolean) to true, which causes tasks to be immediately removed from the work queue at time of cancellation.

这是一个 ScheduledThreadPoolExecutor 方法。我不相信有可能纯粹使用 ScheduledExecutorService 界面来解决这个问题。

This is a ScheduledThreadPoolExecutor method though. I don't believe it's possible to solve this purely using the ScheduledExecutorService interface.