简体   繁体   English

ScheduledExecutorService多次启动停止

[英]ScheduledExecutorService start stop several times

I am using ScheduledExecutorService , and after I call it's shutdown method, I can't schedule a Runnable on it. 我正在使用ScheduledExecutorService ,在我调用它的shutdown方法之后,我无法在其上安排Runnable。 Calling scheduleAtFixedRate(runnable, INITIAL_DELAY, INTERVAL, TimeUnit.SECONDS) after shutdown() throws java.util.concurrent.RejectedExecutionException. shutdown()之后调用scheduleAtFixedRate(runnable, INITIAL_DELAY, INTERVAL, TimeUnit.SECONDS) shutdown()抛出java.util.concurrent.RejectedExecutionException。 Is there another way to run a new task after shutdown() is called on ScheduledExecutorService ? ScheduledExecutorService上调用shutdown()之后是否有另一种方法来运行新任务?

You can reuse the scheduler, but you shouldn't shutdown it. 您可以重用调度程序,但不应该关闭它。 Rather, cancel the running thread which you can get when invoking scheduleAtFixedRate method. 而是取消在调用scheduleAtFixedRate方法时可以获得的正在运行的线程。 Ex: 例如:

//get reference to the future
Future<?> future = service.scheduleAtFixedRate(runnable, INITIAL_DELAY, INTERVAL, TimeUnit.SECONDS)
//cancel instead of shutdown
future.cancel(true);
//schedule again (reuse)
future = service.scheduleAtFixedRate(runnable, INITIAL_DELAY, INTERVAL, TimeUnit.SECONDS)
//shutdown when you don't need to reuse the service anymore
service.shutdown()

The javadocs of shutdown() say: shutdown()的javadocs说:

Initiates an orderly shutdown in which previously submitted tasks are executed,
but no new tasks will be accepted.

So, you cannot call shutdow() and then schedule new tasks. 因此,您无法调用shutdow()然后安排新任务。

You can't make your executor accept new tasks after shutting it down. 关闭后,您无法让执行者接受新任务。 The more relevant question is why you need to shut it down in the first place? 更相关的问题是为什么你需要首先关闭它? The executors you create should be re-used across the lifetime of your application or sub-system. 您创建的执行程序应在应用程序或子系统的整个生命周期内重复使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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