重新启动ScheduledExecutorService计划任务的正确方法是什么?
我有一个计划任务(在固定延迟执行中运行),像这样开始:
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
或者,为什么不在更新中使用新设置或参数重复更新状态? 如果你不需要新的延迟,它甚至不需要重新安排。