首页 > 代码库 > Tomcat启动就执行特定方法

Tomcat启动就执行特定方法

import java.util.Timer;

 

import javax.servlet.ServletContextEvent;

import javax.servlet.ServletContextListener;

 

public class TestListener implements ServletContextListener {

  private Timer timer = null;

 

  public void contextInitialized(ServletContextEvent event) {

    timer = new Timer(true);

    timer.schedule(new TestTimer(), 0, 86400000);//milliseconds

  }

 

  public void contextDestroyed(ServletContextEvent event) {

    timer.cancel();

  }

}

 

------------------------------------------

 

import java.util.TimerTask;

 

public class TestTimer extends TimerTask {

  public void run() {

    // do something ...

  }

}

 

------------------------------------------

 

web.xml:

 

<listener>

<listener-class>test.TestListener</listener-class>

</listener>