JAVA WEB程序中添加定时器


  1. //这是我的定时器类,用来定时执行某段任务;   
  2.     package com.my.time;   
  3.     import java.text.ParseException;   
  4.     import java.text.SimpleDateFormat;   
  5.     import java.util.Date;   
  6.     import java.util.Timer;   
  7.     public class BugXmlTimer  {   
  8.        public   Timer timer;   
  9.          
  10.           
  11.        public void timerStart(){   
  12.            timer = new Timer();   
  13.            Date datetime=new Date();   
  14.            Date midnightDate=new Date();   
  15.            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");   
  16.            SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");   
  17.               
  18.         try {   
  19.                        
  20.             midnightDate = sdf2.parse(sdf1.format(datetime)+" 23:00:00");   
  21.         } catch (ParseException e) {   
  22.             // TODO Auto-generated catch block   
  23.             e.printStackTrace();   
  24.         }   
  25.                
  26.             long in=midnightDate.getTime()-datetime.getTime();   
  27.           
  28.             System.out.println("before task");   
  29.     //立刻执行,然后每隔30s执行一次   
  30.             timer.schedule(new BugXmlTimerTask(), 0,30000);   
  31.                
  32.              
  33.        }   
  34.           
  35.        public void timerStop(){   
  36.            if(timer!=null)    
  37.               timer.cancel();   
  38.        }   
  39.           
  40.        public static void main(String[] args){   
  41.             BugXmlTimer myTimer=new BugXmlTimer();   
  42.                
  43.                 // TODO Auto-generated method stub   
  44.             myTimer.timerStart();   
  45.                
  46.        }   
  47.     }   
  48. //这是执行任务的类,即每隔一段时间要做的事情在这里   
  49.     package com.my.time;   
  50.     import java.util.TimerTask;   
  51.     public class BugXmlTimerTask extends TimerTask {   
  52.         @Override  
  53.         public void run() {   
  54.                System.out.print("run task");   
  55.          }   
  56.     }   
  57.        
  58.        
  59. //以下是出发定时操作的类,该类实现了ServletContextListener   
  60.     public class MyTimerListener implements ServletContextListener {   
  61.         private BugXmlTimer  mytimer = new BugXmlTimer  ();   
  62.         public void contextInitialized(ServletContextEvent event) {   
  63.             mytimer.timerStart();   
  64.         }   
  65.         public void contextDestroyed(ServletContextEvent event) {   
  66.             mytimer.timerStop();   
  67.         }   
  68.     }   
  69.   
  70.   
  71. 然后在web.xml里部署一下,即可在程序启动后运行定时器了!   
  72.      <listener>   
  73.             <listener-class>com.my.time.MyTimerListener </listener-class>   
  74.      </listener>  

相关内容