我有一个计划的任务(以固定延迟执行运行),开始如下:
executoreService.scheduleWithFixedDelay(repeatingThread,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,TimeUnit.SECONDS);
我不确定这些API调用.什么是重新启动任务的推荐方法(可能会有新的延迟)?
解决方法
不,您不想或需要关闭整个服务只是为了修改一个任务.而是使用从服务获得的ScheduledFuture对象来取消任务,然后安排一个新的.
ScheduledFuture<?> future = executorService.scheduleWithFixedDelay(repeatingThread,TimeUnit.SECONDS); ... // to cancel it: future.cancel(true); // then schedule again
或者,为什么不用updateThread更新新的设置或参数的状态?它甚至不需要重新安排,如果你不需要新的延迟.