使用 shutdownNow() 方法时获取我使用 ScheduledThreadPoolExecutor 调度的 Runnable 对象
我正在使用 ScheduledThreadPoolExecutor.schedule(Runnable,int,TimeUnit) 来调度实现 Runnable 的类的一些对象。
在某个时间点,我的应用程序将关闭,我使用 ScheduledThreadPoolExecutor.shutdownNow()。根据文档,它返回 ScheduledFuture 的列表。
我真正想做的是获取我最初安排的对象,并从中获取一些数据,然后我将输出该数据,表示它无法执行。随后,应用程序将使用它来尝试在应用程序重新启动时执行它。
I'm using ScheduledThreadPoolExecutor.schedule(Runnable,int,TimeUnit) to schedule some objects of a class that implements Runnable.
At some point in time, my application is then shutting down, and I use ScheduledThreadPoolExecutor.shutdownNow(). According to the documentation it returns a list of ScheduledFuture's.
What I really want to do is get a hold of the object that I originally scheduled, and get a bit of data from it which I will then output saying that it was unable to execute. This would then, later, be used by the application to attempt to execute it when the application then starts back up.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
获取提交给执行器的对象信息的常用方法是维护一个指向原始对象的指针(它们是 Callable、Runnable 等的扩展)。调用 shutdownNow() 后,并考虑等待执行的 Runnable 返回,您可以使用它来修剪原始对象列表,并仅询问实际运行的对象。
The usual way to get info about objects submitted to an executor is to maintain a pointer to the original objects (be they extensions to Callable, Runnable, etc). After you call shutdownNow(), and take into account the Runnable's returned by that which were awaiting execution, you can use that to prune your original list of objects and just interrogate the ones that were actually run.
如果您只想向用户呈现信息,最简单的方法可能是为您调度的 Runnable 实现有意义的 toString() 方法。然后,您可以简单地迭代
Executor
为您提供的列表并记录您得到的内容。但可悲的事实是,您的原始对象会被
执行器
包装。然后,您需要手动保留传递给 Executor 的内容的列表,并让 Runnable 在执行时从该列表中删除自己。显然,您需要使用线程安全列表来实现此目的。If you just want to present the information to the user, the simplest approach might be to implement a meaningful
toString()
method for theRunnable
s you'r scheduling. Then you can simply iterate the list theExecutor
gives you and log what you get.But the sad truth is that your original objects get wrapped by the
Executor
, though. Then you would need to keep a list of what you pass to theExecutor
manually and let theRunnable
s remove themselves from this list when they get executed. Obviously, you would need to use a thread-safe list for this purpose.