tags:

views:

127

answers:

1

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)?

+3  A: 

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.

Sean Owen
It's something to consider, but it's easier to implement something that will cover any case of a settings change. i.e., any change in the setting file *may* also change the delay. So instead of checking if the delay was changed and then do one thing, and if it wasn't then something else, then I'd rather just restart in any case.
Ovesh