Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the correct way to restart a ScheduledExecutorService scheduled task?

Tags:

java

timer

I have a scheduled task (running in fixed delay execution), started like this:

executoreService.scheduleWithFixedDelay(repeatingThread, 0, numOfSeconds, TimeUnit.SECONDS);

On every start of cycle, I check for a change in a settings file, and then I want to restart the task. The settings file also contains length of the interval (numOfSeconds in the above code).

Currently, I am using the following code to restart the task:

executoreService.shutdownNow();
try {
 while(!executoreService.awaitTermination(5, TimeUnit.SECONDS)){
  logger.debug("awaiting termintation");
 }
} catch (InterruptedException e) {
 logger.debug("interrupted, continuing", e);
}
// initialize startup parameters
init();
// start the main scheduled timer
executoreService.scheduleWithFixedDelay(repeatingThread, 0, numOfSeconds, TimeUnit.SECONDS);

I'm not sure about these API calls. What is the recommended way to restart the task (possibly with a new delay)?

like image 434
Ovesh Avatar asked Feb 16 '10 09:02

Ovesh


People also ask

How does ScheduledExecutorService work?

ScheduledExecutorService is an ExecutorService which can schedule tasks to run after a delay, or to execute repeatedly with a fixed interval of time in between each execution. Tasks are executed asynchronously by a worker thread, and not by the thread handing the task to the ScheduledExecutorService .

Can we use Scheduler in Executor framework?

We can use Executors. newScheduledThreadPool(int corePoolSize) factory method defined by Executors class. It returns a ScheduledExecutorService object which can be type-casted to ScheduledThreadPoolExecutor object. ScheduledThreadPoolExecutor threadPool = (ScheduledThreadPoolExecutor)Executors.

What is Scheduledfuture?

A delayed result-bearing action that can be cancelled. Usually a scheduled future is the result of scheduling a task with a ScheduledExecutorService .


1 Answers

No, you don't want to or need to shut down the whole service just to modify one task. Instead use the ScheduledFuture object you get from the service to cancel the task, and then schedule a new one.

ScheduledFuture<?> future = executorService.scheduleWithFixedDelay(repeatingThread, 0, numOfSeconds, TimeUnit.SECONDS);
...
// to cancel it:
future.cancel(true);
// then schedule again

Alternatively, why not just update state in whatever repeatingThread is with new settings or parameters? it doesn't even need to be rescheduled, if you don't need a new delay.

like image 60
Sean Owen Avatar answered Oct 13 '22 20:10

Sean Owen