- 監聽類
1 package com.xx.model; 2 3 import java.util.Calendar; 4 import java.util.Date; 5 import java.util.Timer; 6 import javax.servlet.ServletContextEvent; 7 import javax.servlet.ServletContextListener; 8 import org.apache.commons.logging.Log; 9 import org.apache.commons.logging.LogFactory; 10 import com.xx.model.XXTask; 11 12 public class XXTimerListener implements ServletContextListener { 13 14 private Timer timer = null; 15 private static final Log log = LogFactory.getLog(XXTimerListener.class); 16 final Log logrecords = LogFactory.getLog("records"); 17 18 public void contextDestroyed(ServletContextEvent arg0) { 19 // TODO Auto-generated method stub 20 21 } 22 23 public void contextInitialized(ServletContextEvent arg0) { 24 // TODO Auto-generated method stub 25 26 try { 27 timer = new Timer(true); 28 try { 29 Calendar calendar = Calendar.getInstance(); 30 calendar.set(Calendar.HOUR_OF_DAY, 10); // 上午10點 31 calendar.set(Calendar.MINUTE, 0); 32 calendar.set(Calendar.SECOND, 0); 33 Date date = calendar.getTime(); // 第一次執行定時任務的時間 34 // 如果第一次執行定時任務的時間 小于當前的時間 35 // 此時要在 第一次執行定時任務的時間加一天,以便此任務在下個時間點執行。如果不加一天,任務會立即執行。 36 if (date.before(new Date())) { 37 date = addDay(date, 1); 38 } 39 timer.schedule(new XXTask(),date,24*3600*1000); 40 log.info("任務創建成功!"); 41 } catch (Exception e) { 42 log.error("任務創建失敗!", e); 43 } 44 } catch (Exception e) { 45 // TODO Auto-generated catch block 46 e.printStackTrace(); 47 } 48 } 49 50 public Date addDay(Date date, int num) { 51 Calendar startDT = Calendar.getInstance(); 52 startDT.setTime(date); 53 startDT.add(Calendar.DAY_OF_MONTH, num); 54 return startDT.getTime(); 55 } 56 }
- 任務類
1 package com.xx.model; 2 import java.util.TimerTask; 3 import org.apache.commons.logging.Log; 4 import org.apache.commons.logging.LogFactory; 5 /** 6 * @author qjl 7 * 8 */ 9 public class XXTask extends TimerTask { 10 11 private static final Log log = LogFactory.getLog(XXTask.class); 12 MeasureCountsAjax mscAjax = new MeasureCountsAjax(); 13 14 @Override 15 public void run() { 16 17 log.debug("定時任務" + new Date(System.currentTimeMillis())); 18 try { 19 //定時任務要執行的方法寫這里 20 } catch (Exception e) { 21 log.error("定時運行失敗", e); 22 } finally { 23 } 24 } 25 }
?
- 在web.xml中增加
1 <listener> 2 <listener-class> 3 com.xx.model.XXTimerListener 4 </listener-class> 5 </listener>
?