gpt4 book ai didi

java - 暂停和恢复计划任务

转载 作者:行者123 更新时间:2023-12-05 06:41:39 24 4
gpt4 key购买 nike

我需要暂停和恢复计划任务。

我看到很多代码示例取消()一个任务,但我也需要恢复/重新启动它。我看到这样做的建议:

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
}
}
}

...然后我需要重新安排而不是重新开始。

这真的是最好的方法吗?

最佳答案

我更喜欢重新安排而不是暂停和恢复。不仅因为我不知道该怎么做,还因为暂停的任务可能不会释放它们的线程。在此期间,即使任务队列中有其他任务在等待,这些执行线程也会阻塞并且什么都不做。

为了不丢失中间结果,您可以将它们放在另一个队列中,该队列在安排新任务之前被拾取。您还可以根据该队列实现暂停和恢复。

关于java - 暂停和恢复计划任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39896597/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com