繁体   English   中英

重新启动ScheduledExecutorService计划任务的正确方法是什么?

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

我有一个计划任务(在固定延迟执行中运行),像这样开始:

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

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

目前,我使用以下代码重新启动任务:

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调用。 重启任务的推荐方法是什么(可能有新的延迟)?

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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