如何在 ExecutorService.shutdown() 之后立即运行未完成的任务?
我有一个 ScheduledExecutorService
,其中的任务计划在一小时内执行。如何获取未完成任务的列表,以便强制它们立即运行?
我相信 shutdown() 会等待一个小时,并且看起来好像 shutdownNow() 返回一个无法 run() 的 Runnable 列表,因为 Runnable 实现会检查 Executor 状态当它注意到它已经关闭时,Runnable 拒绝运行。实际实现请参见ScheduledThreadPoolExecutor.ScheduledFutureTask.run()。
有什么想法吗?
I've got a ScheduledExecutorService
with tasks scheduled to execute in an hour. How do I get the list of outstanding tasks so I can force them to run immediately?
I believe shutdown()
will wait an hour and it looks as if shutdownNow()
returns a list of Runnables that cannot be run() because the Runnable implementation checks the Executor state and when it notices that it has shut down the Runnable refuses to run. See ScheduledThreadPoolExecutor.ScheduledFutureTask.run()
for the actual implementation.
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我采纳了 Mark Peters 的答案,实现了所有抽象方法,添加了线程安全性,并尽可能尊重底层的 ScheduledThreadPoolExecutor 配置。
I've taken Mark Peters' answer, implementing all abstract methods, added thread-safety and tried respecting the underlying ScheduledThreadPoolExecutor configuration whenever possible.
好问题!不过,看起来您可能需要自己拼凑解决方案。
一种选择可能是使用您自己的
ScheduledExecutorService
实现来包装ScheduledThreadPoolExecutor
。当需要关闭服务时,取消任何可以取消的任务,并将它们发送到将立即执行它们的服务。然后shutdown()
该服务。这是一些非常粗略的代码,说明了我的意思,尽管我警告您这里可能存在陷阱,因为它是在几分钟内完成的。特别是,我没有付出太多努力来确保这是线程安全的。
Great question! It looks like you might be on your own patching together a solution though.
One option might be to wrap the
ScheduledThreadPoolExecutor
with your own implementation ofScheduledExecutorService
. When it comes time to shutdown the service, cancel any tasks that can be cancelled and instead send them to a service that will execute them immediately. Thenshutdown()
that service.Here is some very rough code that demonstrates what I mean, though I warn you there may be pitfalls in here since it was whipped up in a few minutes. In particular, I haven't gone to much effort to ensure this is threadsafe.