ScheduledExecutorService start stop several times
Solution 1
You can reuse the scheduler, but you shouldn't shutdown it. Rather, cancel the running thread which you can get when invoking scheduleAtFixedRate method. 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()
Solution 2
The javadocs of shutdown()
say:
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.
Solution 3
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.
Comments
-
walters almost 2 years
I am using ScheduledExecutorService, and after I call it's shutdown method, I can't schedule a Runnable on it. Calling
scheduleAtFixedRate(runnable, INITIAL_DELAY, INTERVAL, TimeUnit.SECONDS)
aftershutdown()
throws java.util.concurrent.RejectedExecutionException. Is there another way to run a new task aftershutdown()
is called on ScheduledExecutorService? -
walters over 13 yearsAny suggestions on how to re-schedule new tasks after shutdown?
-
Peter Knego over 13 yearsEither create a new ScheduledExecutorService or don't shutdown the existing one. Is there a reason you are shutting it down?
-
Eric Thorbjornsen almost 12 yearsI was able to shutdown and create new services in a Spring environment, but EJBs were giving me grief. This did the trick, thanks!
-
Nickolas over 10 years@Alex The first future object will not release, until the service is shutdown. It will be a memory leak when service lives long, and schedule many times. If true, is there a way to avoid memory leaking?
-
Nickolas over 10 yearsI am wrong, the canceled futureTask will not be added to workQueue, so it will be released by GC.