http://blog.csdn.net/smile0198/article/details/17997321
- <listener>
- <listener-class>com.epg.control.listener.TestListener</listener-class>
- </listener>
- package com.epg.control.listener;
- import java.util.Calendar;
- import java.util.Timer;
- import java.util.TimerTask;
- import javax.servlet.ServletContextEvent;
- import javax.servlet.ServletContextListener;
- /**
- * 测试监控
- * @author anjl
- *
- */
- public class TestListener implements ServletContextListener {
- public TestListener() {
- }
- public void contextInitialized(ServletContextEvent arg0) {
- Auto();
- }
- public void contextDestroyed(ServletContextEvent arg0) {
- }
- /**
- * 自动监控方法
- */
- public void Auto() {
- //程序启动后,5秒监控,只跑一次
- Timer time = new Timer();
- time.schedule(new TimerTask() {
- public void run() {
- try{
- listenMethod();
- }catch(Exception e){
- System.out.println("监控出现异常");
- }
- }
- }, 5000);
- //每周六早上8点5分运行,之后每隔一周运行一次
- Timer timer = new Timer();
- Calendar c = Calendar.getInstance();
- c.set(Calendar.DAY_OF_WEEK, 7);//每周六
- c.set(Calendar.HOUR_OF_DAY, 8);//每天8:00运行
- c.set(Calendar.MINUTE, 5);//5分
- c.set(Calendar.SECOND, 0);//秒设置为0
- timer.schedule(new TimerTask() {
- public void run() {
- try{
- listenMethod();
- }catch(Exception e){
- System.out.println("监控出现异常");
- }
- }
- }, c.getTime(), 7*24 * 3600 * 1000);
- }
- public void listenMethod(){
- System.out.println("我在监控!!!");
- }
- }
解释:
TestListener类要implements ServletContextListener
在方法contextInitialized中添加监控方法
public void contextInitialized(ServletContextEvent arg0) {
Auto ();
}
在方法 Auto ()中写监控程序,通过timer来设定执行时间
注意点:
1、run方法中要
捕获异常,否则抛异常给Timer后,Timer会停止
2、如果
指定执行时间已经过了工程部署时间,例如你在周三指定周二执行,那么timer以你部署工程的时间为准来定时执行