Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. Calling scheduleAtFixedRate(runnable, INITIAL_DELAY, INTERVAL, TimeUnit.SECONDS) after shutdown() throws java.util.concurrent.RejectedExecutionException. Is there another way to run a new task after shutdown() is called on ScheduledExecutorService?

like image 547
walters Avatar asked Nov 17 '10 14:11

walters


1 Answers

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()
like image 71
Alex Objelean Avatar answered Oct 11 '22 20:10

Alex Objelean