简体   繁体   中英

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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