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)?
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 .
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.
A delayed result-bearing action that can be cancelled. Usually a scheduled future is the result of scheduling a task with a ScheduledExecutorService .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With