本例依據(jù)Java自身提供的接口實(shí)現(xiàn),通過監(jiān)聽器(Listener)和定時(shí)器(Timer)定時(shí)執(zhí)行某個(gè)任務(wù)(Task)。
專業(yè)的開源工具可參考Quartz:
http://www.opensymphony.com/quartz/
MyListener:
import java.util.Timer;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class MyListener implements ServletContextListener {
private Timer timer = null;
public void contextInitialized(ServletContextEvent event) {
timer = new Timer(true);
//設(shè)置任務(wù)計(jì)劃,啟動(dòng)和間隔時(shí)間
timer.schedule(new MyTask(), 0, 86400000);
}
public void contextDestroyed(ServletContextEvent event) {
timer.cancel();
}
}
MyTask:
import java.util.TimerTask;
public class MyTask extends TimerTask {
public void run() {
// System.out.println("call at " + (new Date()));
// TODO 此處添加具體任務(wù)代碼
}
}
web.xml配置:
<listener>
<listener-class>com.fastunit.samples.listener.MyListener</listener-class>
</listener>