我有一个 ScheduledExecutorService
,它调用 Runnable定期通过 scheduleWithFixedDelay()
(可以使用 scheduleAtFixedRate()
代替)。
我现在正在考虑如果发生错误该怎么办。如果它是无法轻易从(*)恢复的东西,我希望选择停止所有进一步的调用,但不确定执行此操作的最佳方法。
明显检查的异常不能从 Runnable 中抛出,因此希望获得有关如何从以下选项中进行选择的指导:
scheduledFuture.cancel(false);
...or...
scheduledFuture.cancel(true);
...or...
scheduledExecutorService.shutdown();
...or...
scheduledExecutorService.shutdownNow();
...or...
Throw a custom RuntimeException myself?
...or...
Something else?
(*) 想知道一般情况,但如果有人感兴趣,我当前正在查看的已检查异常是 ParserConfigurationException
从 DocumentBuilderFactory.newDocumentBuilder()
抛出。如果抛出此错误,则表明存在严重问题,因此我基本上希望调度完全停止,而不是每次都可能重复错误。
最佳答案
您可以使用 Callable以及 Future也许。这将使您可以从异步任务中抛出已检查的异常,但仍然可以根据每个任务的需要捕获和处理。
如果您使用这种方法,那么允许任务本身决定如何处理异常可能是最有意义的。请参阅这个答案:
但是,如果您想在任务本身之外处理异常,那么我认为每个任务都需要另一个线程。这是一种可能的选择:
ScheduledExecutorService scheduleExecutor;
scheduleExecutor = = Executors.newScheduledThreadPool(10); // or whatever
ExecutorService workerExecutor;
workerExecutor = Executors.newSingleThreadExecutor(); // or whatever
public void schedule(final long fixedDelay) {
scheduleExecutor.scheduleWithFixedDelay(new Runnable() {
@Override
public void run() {
Future<Void> future = workerExecutor.submit(new Callable<Void>() {
@Override
public Void call() throws Exception {
// Do work here. Throw appropiate exception as needed.
return null;
}
});
// Now you can catch and handle the exception in whatever
// way you need to. You can cancel just this task (which is likely
// redundant by this point), or you can choose to shutdown
// all other scheduled tasks (which I doubt is what you want).
try {
future.get();
} catch (Exception e) {
future.cancel(true);
}
}
}, 0, fixedDelay, TimeUnit.MILLISECONDS);
}
关于java - 如何使用 ScheduledExecutorService 处理重复任务中的错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13993911/