我有一个 Runnable
实现,它执行一些可能需要一些时间的工作,我尝试使用 ScheduledThreadPoolExecutor
和 scheduleAtFixedRate
方法来安排它。现在我想确保关闭是正常的,这意味着,在终止之前,应该允许任务完全运行。我编写了以下关闭代码。
public void shutDown() throws Exception {
try {
LOG.info("Gracefully shutting down executor");
executor.shutdown();
if (!executor.awaitTermination(SHUTDOWN_TIMEOUT, TimeUnit.SECONDS)) {
// cancels currently executing tasks.
LOG.info("Executor is still alive. Forcing executor thread pool to shut down");
executor.shutdownNow();
// Wait a while for tasks to respond to being cancelled
if (!executor.awaitTermination(SHUTDOWN_TIMEOUT, TimeUnit.SECONDS)) {
LOG.fatal("Executor thread pool did not terminate");
throw new Exception("Unable to shut down executor thread pool forcefully");
}
LOG.info("Executor shut down.");
}
} catch (Exception e) {
LOG.error("Exception shutting down executor", e);
throw e;
}
}
但问题是,我必须明确指定等待时间,并且我无法提前预测任务所需的时间。有没有办法让执行器无限期地等待,直到执行任务完成,而不必提及等待时间?或者有更好的方法来处理上述场景吗?
谢谢
吉腾德拉
最佳答案
最简单的解决方案就是“过度配置”。我建议您使用一个很大的超时期限,决不能超过单个任务执行所需的时间,例如:
// do you have tasks that can take more than 2^63 - 1 days to finish? :)
executor.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
关于java - 在 ScheduledThreadPoolExecutor 中终止之前等待任务完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9104190/