如何从ScheduledExecutorService的任务?任务、ScheduledExecutorService

2023-09-04 04:44:11 作者:烟花再美丶只是瞬间

我有一个ScheduledExecutorService的那个时代周期性几个不同的任务与 .scheduleAtFixedRate(Runnable接口,INIT_DELAY,ACTION_DELAY,TimeUnit.SECONDS);

I have a ScheduledExecutorService that times a few different task periodically with .scheduleAtFixedRate(Runnable, INIT_DELAY, ACTION_DELAY, TimeUnit.SECONDS);

我也有一个不同的的Runnable 我使用这个调度。 当我想删除从调度的任务之一,这个问题开始。

I also have a different Runnable that I'm using with this scheduler. the problem starts when I want to remove one of the tasks from the scheduler.

有没有办法做到这一点?

is there a way to do this?

我在做使用一个调度程序为不同的任务是正确的? 什么是实现这一目标的最佳方式是什么?

am I doing the right thing using one scheduler for different tasks? what is the best way to implement this?

推荐答案

干脆取消由 scheduledAtFixedRate回到未来()

public static void main(String[] args) throws InterruptedException {
    ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);
    Runnable r = new Runnable() {
        @Override
        public void run() {
            System.out.println("Hello");
        }
    };
    ScheduledFuture<?> scheduledFuture =
        scheduledExecutorService.scheduleAtFixedRate(r, 1L, 1L, TimeUnit.SECONDS);
    Thread.sleep(5000L);
    scheduledFuture.cancel(false);
}

另外要注意的是,取消不会从调度删除该任务。它所保证的是,isDone方法总是返回true。这可能会导致内存泄漏,如果你继续增加这样的任务。对于例如:如果你开始基于一些客户活动或UI按钮,单击任务,重复n次,然后退出。如果该按钮被点击的次数太多,你可能最终与线程不能被垃圾收集调度仍有引用大水池。

Another thing to note is that cancel does not remove the task from scheduler. All it ensures is that isDone method always return true. This may lead to memory leaks if you keep adding such tasks. For e.g.: if you start a task based on some client activity or UI button click, repeat it n-times and exit. If that button is clicked too many times, you might end up with big pool of threads that cannot be garbage collected as scheduler still has a reference.

您可能需要使用setRemoveOnCancelPolicy(真)在Java 7中起可用的ScheduledThreadPoolExecutor类。为了向后兼容,默认设置为false。

You may want to use setRemoveOnCancelPolicy(true) in ScheduledThreadPoolExecutor class available in Java 7 onwards. For backward compatibility, default is set to false.