[英]shutdown only one task in ScheduledExecutorService
I have a few tasks which are registered by我有一些由注册的任务
final ScheduledExecutorService ses = Executors.newScheduledThreadPool(10);
List<ScheduledFuture<?>> futures = new ArrayList<>();
tasks.forEach(task->{
var future = ses.scheduleWithFixedDelay(() -> run(task), 0, 3, TimeUnit.SECONDS);
futures.add(future);
});
// and now cancel all tasks one for one after 10 seconds..
ses.scheduleWithFixedDelay(() ->
{
log.info("cancel task----");
futures.get(0).cancel(false);
}, 0, 10, TimeUnit.SECONDS);
As you can see, for each task the futures
holds a task.getId()
so I can obtain the ScheduledFuture
of a task afterwards.如您所见,对于每个任务,
futures
都有一个task.getId()
因此我可以在之后获取任务的ScheduledFuture
。 I do not want to ses.shutdown()
because this will shutdown the whole schedulings for the other tasks as well, which I want to avoid.我不想
ses.shutdown()
因为这也会关闭其他任务的整个调度,这是我想避免的。
The only solution I actually see is to create one ScheduledExecutorService
for each task to be able to shutdown it afterwards for a specified task, but then I cannot make use of the pooling.我实际看到的唯一解决方案是为每个任务创建一个
ScheduledExecutorService
,以便之后能够为指定的任务关闭它,但是我无法使用池。
How can I shutdown only a specified task within the pool?如何仅关闭池中的指定任务?
Use用
Future<?> future;
future.cancel(false);
Cancel will cancel the task and any further scheduling of it.¹ The Boolean parameter decides if you want to throw an interruption exception on the task if it is already running and blocking on a resource. Cancel 将取消任务和它的任何进一步调度。¹ 布尔参数决定是否要在任务已经运行并阻塞资源时抛出中断异常。
To ensure the task is removed from the queue immediately upon cancelling, use the setRemoveOnCancelPolicy method on your ScheduledThreadPoolExecutor and set the policy to true.²为确保任务在取消后立即从队列中删除,请在 ScheduledThreadPoolExecutor 上使用 setRemoveOnCancelPolicy 方法并将策略设置为 true。²
final ScheduledThreadPoolExecutor ses = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(10);
ses.setRemoveOnCancelPolicy(true);
¹ https://docs.oracle.com/javase/8/docs/api/index.html?java/util/concurrent/Future.html ¹ https://docs.oracle.com/javase/8/docs/api/index.html?java/util/concurrent/Future.html
² https://stackoverflow.com/a/36748183/4425643 , https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ScheduledThreadPoolExecutor.html#setRemoveOnCancelPolicy-boolean- ² https://stackoverflow.com/a/36748183/4425643 , https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ScheduledThreadPoolExecutor.html#setRemoveOnCancelPolicy-boolean-
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.