繁体   English   中英

仅关闭 ScheduledExecutorService 中的一项任务

[英]shutdown only one task in ScheduledExecutorService

我有一些由注册的任务

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);

如您所见,对于每个任务, futures都有一个task.getId()因此我可以在之后获取任务的ScheduledFuture 我不想ses.shutdown()因为这也会关闭其他任务的整个调度,这是我想避免的。

我实际看到的唯一解决方案是为每个任务创建一个ScheduledExecutorService ,以便之后能够为指定的任务关闭它,但是我无法使用池。

如何仅关闭池中的指定任务?

Future<?> future;
future.cancel(false);

Cancel 将取消任务和它的任何进一步调度。¹ 布尔参数决定是否要在任务已经运行并阻塞资源时抛出中断异常。

为确保任务在取消后立即从队列中删除,请在 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://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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM