给客户做的系统里有几个Timer在定时执行
但是客户反应 某些数据没成功,于是看日志发现是由于Timer报错了,任务就终止了。
然后需要改成在Timer报错的时候还要继续执行任务,于是 catch 里面加代码,但是不是很好。
在网上找到一个
java.util.concurrent.ScheduledExecutorService;
于是看介绍修改原Timer的代码为
public static ScheduledExecutorService executorService = Executors
.newScheduledThreadPool(1);
/**
* 1分钟执行一次
*/
public static void runTimer() {
executorService.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
try {
..... } catch (Exception e) {
e.printStackTrace();
}
}
}, 0, 60, TimeUnit.SECONDS);
}这样就达到了我想要的结果
注意:必须加上try catch捕获异常后 才能在异常后继续执行下一次任务,不然任务会挂起什么都不做。
本文介绍了如何使用java.util.concurrent.ScheduledExecutorService改进定时任务处理,确保即使任务中出现异常,也能在catch块内捕获并继续执行下一次任务,避免任务挂起的问题。

1710

被折叠的 条评论
为什么被折叠?



