java - 当一个任务引发异常时,如何让 ScheduledExecutorService 继续执行其他后续任务
问题描述
我有一个执行器每 5 秒执行一次任务
public class ScheduledTaskExecutor {
public int execute(){
ScheduledExecutorService executor = Executors.newScheduledThreadPool(4);
executor.scheduleAtFixedRate(new Task().run,3,5, TimeUnit.SECONDS);
return -1;
}
}
这是任务。我抛出一个IllegalArgumentException
如果X == 4
public class Task {
private static final Logger LOG = LoggerFactory.getLogger(DcEmailTask.class);
private int x = 0;
public Runnable run = () -> {
String currentThread = Thread.currentThread().getName();
x++;
System.out.println("Thread [" + currentThread + "] is executing the task: " + x);
if (x == 4) throw new IllegalArgumentException();
};
}
程序停止执行并且不打印堆栈跟踪。
解决方案
- 实现 ScheduledExecutorService 接口 (SESWrrapper),该接口在其构造函数中接受另一个 ScheduledExecutorService。
- 实现 Runnable 接口 (SafeRunnableWrapper),该接口在其构造函数中接受另一个 Runnable,并在其 run() 方法中捕获异常。
- 如上所述实现 Callable 接口(SafeCallableWrapper)。
- 在 SESWrrapper.(Runnable, long, TimeUnit) 方法中,使用 SafeRunnableWrapper 包装 Runnable 并调用嵌套的 ScheduledExecutorService.schedule()。
推荐阅读
- gradle - 使用 gradle Zip 任务在存档中包含单个目录
- python - 在事件循环中共享队列
- r - ggplot2 和 CSV “发明”不在我输入中的数据
- excel - Excel 单独的单元格值
- angular - ngOnChanges 不会触发更改
- laravel - 如何在laravel中通过href传递参数?
- javascript - 如何使用 CSS 和 html 在容器内动态创建和排列复选框?
- excel - 在 Excel (Powershell) 中强制打开列数据格式 = TEXT 的 CSV
- python - 如何让 Python 程序在一天中的某些时间执行某些任务?
- reactjs - 确保类型 A 扩展类型 B,该类型具有一个字段,该字段是另一个对象的值