如何从后台任务报告进度? [英] How can I report progress from a background task?

查看:237
本文介绍了如何从后台任务报告进度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个在ExecutorService线程池后台执行的长时间运行的任务。在返回进度或中间结果的任务方面,有哪些最佳实践?有没有提供此功能的库?

I have a long running task that is executing in the background on an ExecutorService thread pool. What are some best practices in terms of this task returning progress or intermediate results? Are there any libraries that provide this functionality?

编辑:为了澄清,我说的是向其他代码报告进度,而不是用户。

To clarify, I'm talking about reporting progress to other code, not to the user.

通常我会使用SwingWorker,但是我正在使用Grails应用程序的Java / Groovy后端,我不确定在无头服务器环境中它会如何表现,因为它有EDT绑定。

Normally I would use SwingWorker, but I'm working with a Java/Groovy backend for a Grails app, and I'm unsure how that would behave in a headless server environment since it has EDT ties.

另一个例子是Eclipse RCP中的Jobs框架,但是我需要一些与UI无关的东西。

Another example is the Jobs framework in Eclipse RCP, but I would need something that doesn't have ties to the UI.

推荐答案

嘿,您可以尝试实现Observer模式并让感兴趣的各方订阅工作线程(java.util.Observable或类似的扩展)或其他类管理观察者。

Hey you could possibly try and implement the Observer Pattern and have interested parties subscribe to the worker thread (extension of java.util.Observable or similar) or another Class that manages the observers.

您可以使用java.util.Observer和java.util.Observable
或自己动手。

You could use java.util.Observer and java.util.Observable or roll your own.

实现观察者模式的一些接口的简单示例:

Simple Example of some Interfaces implementing the Observer Pattern:

public interface ObservableSubject<T extends SubjectObserver, V> {

   void registerObserver(T observer);

   void removeObserver(T observer);

   void notifyObservers(V notificationPayload); 

}


public interface SubjectObserver<T> {

   void handleNotification(T notificationPayload);
}

更多信息:维基百科上的观察者模式

这篇关于如何从后台任务报告进度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆