【发布时间】:2017-02-15 05:37:33
【问题描述】:
我需要暂停和恢复计划任务。
我看到了许多取消()任务的代码示例,但我还需要恢复/重新启动它。我看到了这样做的建议:
public void init(){
scheduledTaskExecutor.getScheduledThreadPoolExecutor().setRemoveOnCancelPolicy(true);
}
public void schedule(String id, Runnable task){
ScheduledFuture<?> scheduledFuture = scheduledTaskExecutor.scheduleAtFixedRate(task);
runningTaskRegistry.put(id, task);
}
public void suspend(String id){
ScheduledFuture<?> scheduledFuture = runningTaskRegistry.get(serviceName);
if(scheduledFuture != null){
scheduledFuture.cancel(false);
try{
scheduledFuture.get();
} catch (InterruptedException | ExecutionException | CancellationException e){
// I do not want the currently running task finishing after this point
}
}
}
...然后我需要重新安排而不是重新开始。
这真的是最好的方法吗?
【问题讨论】:
-
一般来说,是的,重新安排你的任务是最好的方法。想到的一个技巧是使用single-thread executor,并传递给它一个等待暂停条件为假的任务。
-
单线程执行器在这里不是一个选项:我有几十个长时间运行的进程要运行,其中一些运行时间很长。
-
老问题,但是如果在使用任务计划程序 GUI 时禁用选项(与结束选项不同)可用,那么为什么 schtasks 不支持它?您甚至可以使用 schtasks /query 看到禁用的任务显示为禁用。对我来说,这似乎是雷德蒙德的能力不足。
标签: java concurrency scheduled-tasks scheduling