2010-06-21 95 views
4

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

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

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

回答

17

功能要求不明,但回答实际问题:是的,可以在servletcontainer中运行后台进程。

如果您想要一个应用程序范围的后台线程,请使用ServletContextListener钩住webapp的启动和关闭并使用ExecutorService来运行它。作为web.xml如下代替

@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,注册吧:如果你想要一个sessionwide后台线程

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

,使用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. 
    } 

} 

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

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

谢谢您的重播。 对不起。该请求问我是否实施了一种上传某些数据(以数据库加载的新数据)发送电子邮件(警报)的方式。 我曾经想过通过修改现有的Web应用程序来实现这种机制,创建轮询新数据的后台进程。 数据由我不管理的某个其他应用程序加载。 Servlet容器是Tomcat。 感谢您的回答 – sangi 2010-06-21 13:35:37

+0

为什么不直接在用DB更新数据的代码之后直接写这个? – BalusC 2010-06-21 13:48:14

+0

因为我无法访问加载数据的应用程序:它由我无法访问的其他人管理和开发。 – sangi 2010-06-22 17:13:11

0

谢谢!我想知道这是否应该更好地在请求范围内完成,例如:

public class StartServlet extends HttpServlet { 

    @Override 
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
      throws ServletException, IOException {     
     request.getSession().setAttribute("task", new Task());  
    } 
} 

这样,当用户离开页面时,进程停止。