分兩步走:
(1)實現 javax.servlet.ServletContextListener
接口的兩個方法:contextInitialized()和contextDestroyed()
contextInitialized():當Servlet容器啟動時會執行contextDestroyed():當Servlet容器停止時會執行
(2)在contextInitialized()中加入需要監聽的程序,并由 java.util.Timer 的
schedule() 方法來控制監聽程序執行的頻率
DEMO(這是我的監聽的程序原型)
package com.company.servlet;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Timer;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import com.company.task.ClearApplicationAttributeTask;
public class TaskListener implements ServletContextListener {
private static Timer timer = null;
private static ClearApplicationAttributeTask caaTask = null;
public void contextDestroyed(ServletContextEvent arg0) {
//終止此計時器,丟棄所有當前已安排的任務
if(timer != null)
timer.cancel();
}
public void contextInitialized(ServletContextEvent arg0) {
caaTask = new ClearApplicationAttributeTask(arg0.getServletContext());
timer = new Timer(true);
// 定義任務時間,每天0時執行
GregorianCalendar now = new GregorianCalendar();
now.set(Calendar.HOUR, 0);
now.set(Calendar.MINUTE, 0);
now.set(Calendar.SECOND, 0);
timer.schedule(caaTask, now.getTime());
}
}
package com.company.task;
import java.util.TimerTask;
import javax.servlet.ServletContext;
public class ClearApplicationAttributeTask extends TimerTask {
private ServletContext context = null;
public ClearApplicationAttributeTask(ServletContext sc)
{
this.context = sc;
}
public void run()
{
// 在這里可以做一些想做的事情,比如清空application中的屬性
context.removeAttribute("app_name");
}
}
將編譯好的class文件放入WEB-INF/classes中,最后別忘記了在Servlet容器中當前WEB應用的web.xml中加入監聽語句:
<listener>
<listener-class>com.company.servlet.TaskListener</listener-class>
</listener>