2012-07-23 77 views
0

我有一個listener project,我想實現一個web版本。我需要它在部署後持續運行。換句話說,只要應用程序部署到Apache Tomcat 7.0.14.0上,應立即開始監聽/連續運行,而不會影響其他Web應用程序。這可能嗎?在部署中持續運行類

+1

你的意思是一個'ServletContextListener'? – 2012-07-23 07:55:28

+0

是的,但它有可能讓它在後臺運行?如果你嘗試運行index.jsp,它只會在'contextInitialized'進程完成後纔在瀏覽器中打開(即使你在一個'new Thread()'運行進程。 – ThreaT 2012-07-23 08:13:16

+0

並非如此 - 如果你運行在一個單獨的線程中,contextInitialized方法將會返回,並且所有東西都會像平常一樣繼續 – Bozho 2012-07-23 08:23:52

回答

1

從您所描述的內容看,Tomcat希望ServletContext偵聽器能夠完成,然後再進入下一個部署階段。在這種情況下,您可以將您希望發生在後臺的工作放到Runnable類中。

RunClassOnDeployment.java

package web.deployment; 

import javax.servlet.ServletContext; 

public class RunClassOnDeployment implements Runnable { 

    ServletContext myServletContext; // in case you need the servelet context 

    RunClassOnDeployment(ServletContext sc) { 
      myServletContext = sc; 
    } 

    public void run() { 
     Thread th = new Thread(); 
     try { 
      for (int i = 1; i <= 100; i++) { 
       System.out.println(i); 
       th.sleep(1000); 
      } 
     } catch (InterruptedException e) { 
      System.out.println("Thread interrupted! " + e); 
     } 
    } 
} 

,並設置關閉使用監聽器內的ExecutorService:

MyListener.java

package web.deployment; 

import java.util.concurrent.ExecutorService; 
import java.util.concurrent.Executors; 
import javax.servlet.ServletContextEvent; 
import javax.servlet.ServletContextListener; 

public class MyListener implements ServletContextListener { 

    @Override 
    public void contextDestroyed(ServletContextEvent arg0) { 
     System.out.println("ServletContextListener destroyed"); 
    } 

    @Override 
    public void contextInitialized(ServletContextEvent arg0) { 
     ExecutorService executorService = Executors.newSingleThreadExecutor(); 
     executorService.submit(new RunClassOnDeployment(arg0.getServletContext())); 
    } 
} 

的web.xml

<?xml version="1.0" encoding="UTF-8"?> 
<web-app version="2.5" 
     xmlns="http://java.sun.com/xml/ns/javaee" 
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> 
    <listener> 
     <listener-class>web.deployment.MyListener</listener-class> 
    </listener> 
</web-app> 

Download的例子

1

你忘了啓動線程

@Override 
    public void contextInitialized(ServletContextEvent arg0) { 
     Thread th = new Thread(); 
.... 
th.start(); 
} 

但隨着ExecutorService的解決辦法是安靜的更好!

而且......如果需要,您應該自動啓動您的應用程序。

<load-on-startup>100</load-on-startup> 
+0

哦,當然,我錯過了原來的帖子。 – 2012-07-23 12:42:45