Servlet中的后台进程

san*_*ngi 3 servlets background process

是否可以在servlet中实现后台进程!?

让我解释.我有一个servlet,显示一些数据并生成一些报告.报告的生成意味着数据已经存在,就是这样:其他人上传这些数据.

除了生成报告之外,我还应该实现一种在新数据到达时发送电子邮件(上传)的方法.

Bal*_*usC 17

功能需求尚不清楚,但回答实际问题:是的,可以在servletcontainer中运行后台进程.

如果您想要一个应用程序范围的后台线程,请使用ServletContextListener挂钩webapp的启动和关闭并使用ExecutorService它来运行它.

@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();
    }

}
Run Code Online (Sandbox Code Playgroud)

如果您还没有使用Servlet 3.0而无法使用@WebListener,请将其注册如下web.xml:

<listener>
    <listener-class>com.example.Config</listener-class>
</listener>
Run Code Online (Sandbox Code Playgroud)

如果您想要一个会话范围的后台线程,请使用HttpSessionBindingListener它来启动和停止它.

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.
    }

}
Run Code Online (Sandbox Code Playgroud)

在第一次创建和开始时,就这样做

request.getSession().setAttribute("task", new Task());
Run Code Online (Sandbox Code Playgroud)