簡體   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