java深度探究--java监控程序思路--Listener,Timer监控--定时任务

http://blog.csdn.net/smile0198/article/details/17997321

  1.  <listener>  
  2.     <listener-class>com.epg.control.listener.TestListener</listener-class>  
  3.   </listener> 


  1. package com.epg.control.listener;  
  2.   
  3. import java.util.Calendar;  
  4. import java.util.Timer;  
  5. import java.util.TimerTask;  
  6.   
  7. import javax.servlet.ServletContextEvent;  
  8. import javax.servlet.ServletContextListener;  
  9.   
  10. /** 
  11.  * 测试监控 
  12.  * @author anjl 
  13.  * 
  14.  */  
  15. public class TestListener implements ServletContextListener {  
  16.   
  17.     
  18.   public TestListener() {  
  19.   
  20.   }  
  21.   
  22.   public void contextInitialized(ServletContextEvent arg0) {  
  23.       Auto();  
  24.   }  
  25.   
  26.   public void contextDestroyed(ServletContextEvent arg0) {  
  27.   
  28.   }  
  29.   
  30.   /** 
  31.    * 自动监控方法 
  32.    */  
  33.   public void Auto() {  
  34.       
  35.     //程序启动后,5秒监控,只跑一次  
  36.     Timer time = new Timer();  
  37.     time.schedule(new TimerTask() {  
  38.       public void run() {  
  39.         try{  
  40.           listenMethod();  
  41.         }catch(Exception e){  
  42.           System.out.println("监控出现异常");  
  43.         }  
  44.        }  
  45.     }, 5000);  
  46.       
  47.     //每周六早上8点5分运行,之后每隔一周运行一次  
  48.     Timer timer = new Timer();  
  49.     Calendar c = Calendar.getInstance();  
  50.     c.set(Calendar.DAY_OF_WEEK, 7);//每周六  
  51.     c.set(Calendar.HOUR_OF_DAY, 8);//每天8:00运行  
  52.     c.set(Calendar.MINUTE, 5);//5分  
  53.     c.set(Calendar.SECOND, 0);//秒设置为0  
  54.     timer.schedule(new TimerTask() {  
  55.       public void run() {  
  56.         try{  
  57.           listenMethod();  
  58.         }catch(Exception e){  
  59.           System.out.println("监控出现异常");  
  60.         }  
  61.       }  
  62.     }, c.getTime(), 7*24 * 3600 * 1000);  
  63.   
  64.   }  
  65.     
  66.   public void listenMethod(){  
  67.     System.out.println("我在监控!!!");  
  68.   }  
  69.   

解释:

TestListener类要implements ServletContextListener

在方法contextInitialized中添加监控方法
public void contextInitialized(ServletContextEvent arg0) {
       Auto ();
  }
在方法  Auto ()中写监控程序,通过timer来设定执行时间

注意点:

1、run方法中要 捕获异常,否则抛异常给Timer后,Timer会停止
2、如果 指定执行时间已经过了工程部署时间,例如你在周三指定周二执行,那么timer以你部署工程的时间为准来定时执行


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wsxlgg

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值