new Timer().scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
System.out.println("run");
throw new SomeRandomException();
}
}, 1000, 1000);
输出:运行(抛出异常)
问题是:我需要一个计时器任务来检查数据库(或其他内容)中的特定条件。它工作正常,但有时数据库(或其他东西)返回一些错误,抛出异常并且计时器崩溃,然后不再执行单个计时器任务。是否有一些计时器实现在抛出异常后继续工作run()
.
I can
new Timer().scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
try {
System.out.println("run");
throw new SomeRandomException();
} catch (Exception e) {
System.out.println("dummy catch");
}
}
}, 1000, 1000);
但这似乎很蹩脚。
另一种选择是编写我自己的 Timer 类实现,吞掉 run 方法的异常(这似乎也不正确)。
Use a ScheduledExecutorService http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/Executors.html#newScheduledThreadPool%28int%29。它的作用与计时器相同,但修复了它的弱点(就像您遇到的那样)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)