启动ScheduledExecutorService计划任务的正

启动ScheduledExecutorService计划任务的正

本文介绍了重新启动ScheduledExecutorService计划任务的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个计划任务(以固定延迟执行运行),如下所示:

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

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

在每个周期开始时,我检查设置文件中的更改,然后我想要重启任务。设置文件还包含间隔的长度(上面代码中的 numOfSeconds )。

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

我不确定这些API调用。重启任务的推荐方法是什么(可能有新的延迟)?

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

推荐答案

不,你不想或者需要关闭整个服务只是为了修改一个任务。而是使用从服务获得的ScheduledFuture对象来取消任务,然后安排一个新任务。

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

或者,为什么不只是更新状态,无论repeatThread是什么新设置或参数?如果你不需要新的延迟,它甚至不需要重新安排。

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.

这篇关于重新启动ScheduledExecutorService计划任务的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-26 06:38