使用 shutdownNow() 方法时获取我使用 ScheduledThreadPoolExecutor 调度的 Runnable 对象

发布于 2024-10-13 03:07:33 字数 429 浏览 3 评论 0原文

我正在使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

尘曦 2024-10-20 03:07:33

获取提交给执行器的对象信息的常用方法是维护一个指向原始对象的指针(它们是 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.

九八野马 2024-10-20 03:07:33

如果您只想向用户呈现信息,最简单的方法可能是为您调度的 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 the Runnables you'r scheduling. Then you can simply iterate the list the Executor 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 the Executor manually and let the Runnables remove themselves from this list when they get executed. Obviously, you would need to use a thread-safe list for this purpose.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文