JAVA 定時器

定時執行任務的三種方法:
  1)java.util.Timer.
  2)ServletContextListener.
  3)org.springframework.scheduling.timer.ScheduledTimerTask
  1)java.util.Timer
  這個方法應該是最常用的,不過這個方法需要手工啓動你的任務:
  Timer timer=new Timer();
  timer.schedule(new ListByDayTimerTask(),10000,86400000);
  這裏的ListByDayTimerTask類必須extends TimerTask裏面的run()方法。
  2)ServletContextListener
  這個方法在web容器環境比較方便,這樣,在web server啓動後就可以
  自動運行該任務,不需要手工操作。
  將ListByDayListener implements ServletContextListener接口,在
  contextInitialized方法中加入啓動Timer的代碼,在contextDestroyed
  方法中加入cancel該Timer的代碼;然後在web.xml中,加入listener:
  
  com.sysnet.demo.util.MyTimerTask
  
  3)org.springframework.scheduling.timer.ScheduledTimerTask
  如果你用spring,那麼你不需要寫Timer類了,在schedulingContext-timer
  .xml中加入下面的內容就可以了:
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  10000
  
  
  86400000
  
  
  
  下面給出方法2的一個例子供大家參考:
  Java代碼:
  import java.util.Timer;
  import javax.servlet.ServletContextEvent;
  import javax.servlet.ServletContextListener;
  public class MyTimerTask implements ServletContextListener{
  private Timer timer = null;
  @Override
  public void contextDestroyed(ServletContextEvent event) {
  // TODO Auto-generated method stub
  timer.cancel();
  event.getServletContext().log("定時器銷燬");
  System.out.println("停止備份程序……");
  }
  @Override
  public void contextInitialized(ServletContextEvent event) {
  //在這裏初始化監聽器,在tomcat啓動的時候監聽器啓動,考試,大提示可以在這裏實現定時器功能
  timer = new Timer(true);
  event.getServletContext().log("定時器已啓動");//添加日誌,可在tomcat日誌中查看到
  timer.schedule(new exportHistoryBean(event.getServletContext()),0,5*1000);//調用exportHistoryBean,0表示任務無延遲,5*1000表示每隔5秒執行任務,60*60*1000表示一個小時;
  }
  }
  import java.util.Calendar;
  import java.util.TimerTask;
  import javax.servlet.ServletContext;
  public class exportHistoryBean extends TimerTask
  {
  private static final int C_SCHEDULE_HOUR = 0;
  private static boolean isRunning = false;
  private ServletContext context = null;
  public exportHistoryBean(ServletContext context)
  {
  this.context = context;
  }
  @Override
  public void run()
  {
  Calendar c = Calendar.getInstance();
  if(!isRunning)
  {
  if(C_SCHEDULE_HOUR == c.get(Calendar.HOUR_OF_DAY))
  {
  isRunning = true;
  context.log("開始執行指定任務");
  isRunning = false;
  context.log("指定任務執行結束");
  }
  else
  {
  context.log("上一次任務執行還未結束");
  }
  }
  }
  }
  web.xml里加入一下代碼:
  
  com.sysnet.demo.util.MyTimerTask
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章