在tomcat中可以注册ServletContextListener,
public void contextInitialized(ServletContextEvent sce);
public void contextDestroyed(ServletContextEvent sce);
答应程序在系统启动和关闭的时候作一些工作。我把线程的启动和关闭都放在这里了,这样系统在reload的时候,也会调用ServletContextListener的方法。
package market;
/**
* 侦听器程序测试
*/
public class marketListener implements Javax.servlet.ServletContextListener {
private java.util.Timer timer;
public marketListener() {
System.out.println( "startup init" );
timer = new java.util.Timer( true );
}
public void contextDestroyed( javax.servlet.ServletContextEvent event ) {
System.out.println( "destory" );
timer.cancel();
}
public void contextInitialized( javax.servlet.ServletContextEvent event ) {
System.out.println( "start" );
System.out.println( event.getServletContext().getRealPath( "/" ) );
timer.schedule( new java.util.TimerTask() {
public void run() {
System.out.println( "TimerTask run..." );
}
} , 0 , 1000 );
}
}
对web.XML的配置
<listener>
<listener-class>market.marketListener</listener-class>
</listener>