部署时连续运行类

时间:2012-07-23 07:49:14

标签: java tomcat

我有一个listener project我希望实现一个网络版本。我需要它在部署时持续运行。换句话说,只要将应用程序部署到 Apache Tomcat 7.0.14.0 上,它就应该立即开始监听/运行,而不会影响Web应用程序的其余部分。这可能吗?

2 个答案:

答案 0 :(得分: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 :(得分:1)

你忘了开始你的线程

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

但是ExecutorService的解决方案更安静了!

并且......如果你愿意的话,你应该自动启动你的应用程序。

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