现在的位置: 首页 > 综合 > 正文

JAVA WEB程序中添加定时器

2018年01月09日 ⁄ 综合 ⁄ 共 1833字 ⁄ 字号 评论关闭
 

//这是我的定时器类,用来定时执行某段任务;

  1. package com.my.time;
  2. import java.text.ParseException;
  3. import java.text.SimpleDateFormat;
  4. import java.util.Date;
  5. import java.util.Timer;
  6. public
     
    class
     BugXmlTimer  {
  7.    
    public
       Timer timer;
  8.   
  9.    
  10.    
    public
     
    void
     timerStart(){
  11.        timer = 
    new
     Timer();
  12.        Date datetime=
    new
     Date();
  13.        Date midnightDate=
    new
     Date();
  14.        SimpleDateFormat sdf1 = 
    new
     SimpleDateFormat(
    "yyyy-MM-dd"
    );
  15.        SimpleDateFormat sdf2 = 
    new
     SimpleDateFormat(
    "yyyy-MM-dd HH:mm:ss"
    );
  16.        
  17.     
    try
     {
  18.                 
  19.         midnightDate = sdf2.parse(sdf1.format(datetime)+
    " 23:00:00"
    );
  20.     } 
    catch
     (ParseException e) {
  21.         
    // TODO Auto-generated catch block
  22.         e.printStackTrace();
  23.     }
  24.         
  25.         
    long
     
    in
    =midnightDate.getTime()-datetime.getTime();
  26.    
  27.         System.
    out
    .println(
    "before task"
    );
  28. //立刻执行,然后每隔30s执行一次
  29.         timer.schedule(
    new
     BugXmlTimerTask(), 0,30000);
  30.         
  31.       
  32.    }
  33.    
  34.    
    public
     
    void
     timerStop(){
  35.        
    if
    (timer!=
    null
  36.           timer.cancel();
  37.    }
  38.    
  39.    
    public
     
    static
     
    void
     main(String[] args){
  40.         BugXmlTimer myTimer=
    new
     BugXmlTimer();
  41.         
  42.             
    // TODO Auto-generated method stub
  43.         myTimer.timerStart();
  44.         
  45.    }
  46. }

//这是执行任务的类,即每隔一段时间要做的事情在这里

  1. package com.my.time;
  2. import java.util.TimerTask;
  3. public
     
    class
     BugXmlTimerTask extends TimerTask {
  4.     @Override
  5.     
    public
     
    void
     run() {
  6.            System.
    out
    .print(
    "run task"
    );
  7.      }
  8. }

//以下是出发定时操作的类,该类继承了ServletContextListener

  1. public
     
    class
     MyTimerListener implements ServletContextListener {
  2.     
    private
     BugXmlTimer  mytimer = 
    new
     BugXmlTimer  ();
  3.     
    public
     
    void
     contextInitialized(ServletContextEvent 
    event
    ) {
  4.         mytimer.timerStart();
  5.     }
  6.     
    public
     
    void
     contextDestroyed(ServletContextEvent 
    event
    ) {
  7.         mytimer.timerStop();
  8.     }
  9. }

 

然后在web.xml里部署一下,即可在程序启动后运行定时器了!

  1.  <listener>
  2.         <listener-
    class
    >com.my.time.MyTimerListener </listener-
    class
    >
  3.  </listener>

抱歉!评论已关闭.