在Servlet的后台进程 [英] Background process in Servlet

查看:100
本文介绍了在Servlet的后台进程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能实现一个后台进程在servlet!?

Is it possible to implement a background process in a servlet!?

让我解释一下。
我有一个servlet,显示一些数据,并生成一些报告。
报告的生成意味着该数据是已经present,而且它是这样的:别人上传这些数据

Let me explain. I have a servlet that shows some data and generate some reports. The generation of the report implies that the data is already present, and it is this: someone else upload these data.

除了生成报告,我应该实现一个方法来对新数据的到来(上载)发送电子邮件。

In addition to report generation, I should implement a way to send an email on arrival of new data (uploaded).

推荐答案

的功能要求还不清楚,但回答的实际的问题:是的,有可能在servletcontainer运行一个后台进程

The functional requirement is unclear, but to answer the actual question: yes, it's possible to run a background process in servletcontainer.

如果你想要一个应用程序范围后台线程,使用<一个href=\"http://docs.oracle.com/javaee/6/api/javax/servlet/ServletContextListener.html\"><$c$c>ServletContextListener钩上的web应用的启动和关闭,并使用<一个href=\"http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/ExecutorService.html\"><$c$c>ExecutorService运行它。

If you want an applicationwide background thread, use ServletContextListener to hook on webapp's startup and shutdown and use ExecutorService to run it.

@WebListener
public class Config implements ServletContextListener {

    private ExecutorService executor;

    public void contextInitialized(ServletContextEvent event) {
        executor = Executors.newSingleThreadExecutor();
        executor.submit(new Task()); // Task should implement Runnable.
    }

    public void contextDestroyed(ServletContextEvent event) {
        executor.shutdown();
    }

}

如果你的Servlet 3.0是没有,因此无法使用 @WebListener ,其注册在如下的web.xml 而不是:

If you're not on Servlet 3.0 yet and thus can't use @WebListener, register it as follows in web.xml instead:

<listener>
    <listener-class>com.example.Config</listener-class>
</listener>


如果你想有一个sessionwide后台线程,使用<一个href=\"http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpSessionBindingListener.html\"><$c$c>HttpSessionBindingListener启动和停止它。


If you want a sessionwide background thread, use HttpSessionBindingListener to start and stop it.

public class Task extends Thread implements HttpSessionBindingListener {

    public void run() {
        while (true) {
            someHeavyStuff();
            if (isInterrupted()) return;
        }
    }

    public void valueBound(HttpSessionBindingEvent event) {
        start(); // Will instantly be started when doing session.setAttribute("task", new Task());
    }

    public void valueUnbound(HttpSessionBindingEvent event) {
        interrupt(); // Will signal interrupt when session expires.
    }

}

在第一的创建和启动,只是做

On first creation and start, just do

request.getSession().setAttribute("task", new Task());

这篇关于在Servlet的后台进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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