ScheduledExecutorService 异常处理 [英] ScheduledExecutorService Exception handling
本文介绍了ScheduledExecutorService 异常处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用 ScheduledExecutorService 定期执行一个方法.
I use ScheduledExecutorService to execute a method periodically.
p 代码:
ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
ScheduledFuture<?> handle =
scheduler.scheduleWithFixedDelay(new Runnable() {
public void run() {
//Do business logic, may Exception occurs
}
}, 1, 10, TimeUnit.SECONDS);
我的问题:
如果run()
抛出异常,如何继续调度程序?我应该尝试捕获方法 run()
中的所有异常吗?或者任何内置的回调方法来处理异常?谢谢!
How to continue the scheduler, if run()
throws Exception?
Should I try-catch all Exception in method run()
? Or any built-in callback method to handle the Exception? Thanks!
推荐答案
你应该像这样使用 scheduler.scheduleWithFixedDelay(...)
返回的 ScheduledFuture
对象:
You should use the ScheduledFuture
object returned by your scheduler.scheduleWithFixedDelay(...)
like so :
ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
ScheduledFuture<?> handle =
scheduler.scheduleWithFixedDelay(new Runnable() {
public void run() {
throw new RuntimeException("foo");
}
}, 1, 10, TimeUnit.SECONDS);
// Create and Start an exception handler thread
// pass the "handle" object to the thread
// Inside the handler thread do :
....
try {
handle.get();
} catch (ExecutionException e) {
Exception rootException = e.getCause();
}
这篇关于ScheduledExecutorService 异常处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文