当scheduleWithFixedDelay抛出异常时如何重新启动计划? [英] How to restart schedule when scheduleWithFixedDelay throws an exception?
问题描述
我使用 ScheduledExecutorService
来计划一些需要定期运行的任务。
我想知道这个代码是否在异常发生时恢复调度。
I use ScheduledExecutorService
to schedule some tasks which need to run periodically.
I want to know whether this code works to recover the schedule when an exception happens.
ScheduledExecutorService service = Executors.newScheduledThreadPool(1);
this.startMemoryUpdateSchedule(service);//See below method
//Recursive method to handle exception when run schedule task
private void startMemoryUpdateSchedule(ScheduledExecutorService service) {
ScheduledFuture<?> future = service.scheduleWithFixedDelay(new MemoryUpdateThread(), 1, UPDATE_MEMORY_SCHEDULE, TimeUnit.MINUTES);
try {
future.get();
} catch (ExecutionException e) {
e.printStackTrace();
logger.error("Exception thrown for thread",e);
future.cancel(true);
this.startMemoryUpdateSchedule(service);
} catch(Exception e) {
logger.error("Other exception ",e);
}
}
推荐答案
应该在 while(true)
循环中包含try块,因为如果第一次运行不抛出异常,您将退出您的方法,如果第二次调用抛出一个异常,你不会捕获它。
You should probably enclose the try block in a while(true)
loop because if the first run does not throw an exception, you will exit your method and if the second call throws one, you won't catch it.
我也会在自己的线程中运行递归调用,以避免在事情变坏时出现StackOverFlow错误。
I would also run the recursive call in its own thread to avoid the risk of a StackOverFlow error if things go bad.
所以它看起来像这样:
private void startMemoryUpdateSchedule(final ScheduledExecutorService service) {
final ScheduledFuture<?> future = service.scheduleWithFixedDelay(new MemoryUpdateThread(), 1, UPDATE_MEMORY_SCHEDULE, TimeUnit.MINUTES);
Runnable watchdog = new Runnable() {
@Override
public void run() {
while (true) {
try {
future.get();
} catch (ExecutionException e) {
//handle it
startMemoryUpdateSchedule(service);
return;
} catch (InterruptedException e) {
//handle it
return;
}
}
}
};
new Thread(watchdog).start();
}
这篇关于当scheduleWithFixedDelay抛出异常时如何重新启动计划?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!