分两步走:
(1). 实现 javax.servlet.ServletContextListener 接口的两个方法:contextInitialized()和contextDestroyed()
contextInitialized():当Servlet容器启动时会执行
contextDestroyed():当Servlet容器停止时会执行
(2). 在contextInitialized()中加入需要监听的程序,并由 java.util.Timer 的 schedule() 方法来控制监听程序执行的频率
DEMO(这是我的一个短信回复监听的程序原型,精简了一下)
----------------------------------------------------------------
ReplyListener.java
----------------------------------------------------------------
package com.hanweb.jcms;
import javax.servlet.*;
public class ReplyListener implements ServletContextListener {
private ReplyTimer rt = null;
public void contextInitialized(ServletContextEvent event) {
String status = "[SYS] SMS reply listener start .";
event.getServletContext().log(status);
System.out.println(status);
rt = new ReplyTimer(1);
rt.start();
}
public void contextDestroyed(ServletContextEvent event) {
String status = "[SYS] SMS reply listener stop .";
event.getServletContext().log(status);
System.out.println(status);
if (rt != null) {
rt.stop();
}
}
}
----------------------------------------------------------------