[英]Pause and resume scheduled task
我需要暂停并恢复计划的任务。
我看到了许多代码示例来取消()一个任务,但是我还需要恢复/重新启动它。 我看到这样做的建议:
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
}
}
}
...然后我需要重新安排而不是重新计划。
那真的是最好的方法吗?
与暂停和恢复相比,我更喜欢重新安排时间。 不仅因为我不知道如何执行此操作,还因为暂停的任务可能不会释放其线程。 在这段时间内,即使任务队列中还有其他任务在等待,这些执行程序线程也会阻塞并且不执行任何操作。
为了不丢失中间结果,您可以将它们放在另一个队列中,在计划新任务之前将它们拾取。 您还可以基于该队列来实现暂停和恢复。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.