2010-06-21 103 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());  
    } 
} 

這樣,當用戶離開頁面時,進程停止。