java web定時任務調度總結

來源:互聯網
上載者:User

標籤:form   out   oid   nap   ==   private   執行   構造   cancel   

 

有時間我們需要伺服器在夜深人靜的時候,默默執行調度任務。基於java tomcat 的調度任務由以下兩種方式(親自實踐過):

一、實現ServletContextListener類

1.SysContextListener類(配置任務定時掃描)

 1 package com.srba.task; 2  3  4 import java.util.Timer;//定時器類  5  6 import javax.servlet.ServletContextEvent; 7 import javax.servlet.ServletContextListener;  8 public class SysContextListener implements ServletContextListener  9 { 10   private Timer timer = null; 11   //重寫contextInitialized 12   public void contextInitialized(ServletContextEvent event) 13   { 14       //在這裡初始化監聽器,在tomcat啟動的時候監聽器啟動,可以在這裡實現定時器功能 15       timer = new Timer(true); 16       //添加日誌,可在tomcat日誌中查看到 17       event.getServletContext().log("定時器已啟動"); 18       System.out.println("+++++++++++++++++++++++++++系統每天調度任務已開啟,正在保護地球安全!++++++++++++++++++++++++++++");19         int i=1000;       //1000毫秒及1秒20         int s=1000*60*60; //每60分鐘執行一次(可以改成1000*2,每2秒掃描一次)21         Timer timer=new Timer();22          //調用定時任務,i表示任務無延遲,s表示每隔s毫秒執行任務,觸發間隔以毫秒計算。 1秒=1000毫秒。23         timer.schedule(new TimerAction(event), i, s);24       event.getServletContext().log("已經新增工作"); 25   } 26   //重寫contextDestroyed 27   public void contextDestroyed(ServletContextEvent event) 28   { 29       //在這裡關閉監聽器,所以在這裡銷毀定時器。 30       timer.cancel(); 31       event.getServletContext().log("定時器銷毀"); 32   } 33 } 

 

2.TimerAction類(具體要執行的任務)

 1 package com.srba.task; 2  3  4 import java.sql.SQLException; 5 import java.text.DateFormat; 6 import java.text.SimpleDateFormat; 7 import java.util.Date; 8 import java.util.TimerTask; 9 10 import javax.servlet.ServletContextEvent;11 12 import com.srba.web.AllUserInfoMaintenance; 13 public class TimerAction extends TimerTask { 14     private ServletContextEvent myevent;15     TimerAction(ServletContextEvent event){16         this.myevent = event;17     }18         public void run() {19             SimpleDateFormat sdf=new SimpleDateFormat("HH");//可以改成new SimpleDateFormat("ss"),精確到秒20             DateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");21             if(sdf.format(new Date()).equals("01")){// 每天淩晨01點22                 Date beginDate = new Date();23                 myevent.getServletContext().log("現在【"+myFormat.format(beginDate)+"】開始執行同步任務!");24                 AllUserInfoMaintenance task = new AllUserInfoMaintenance();25                 try {26                     task.doUpdate();27                     Date endDate = new Date();28                     myevent.getServletContext().log("現在【"+myFormat.format(endDate)+"】執行同步任務結束!");29                 } catch (SQLException e) {30                     e.printStackTrace();31                 }32             }33         }34     35 } 

3.在項目的web.xml中的<web-app>節點中加入以下內容(注意包的路徑):

  <listener>     <listener-class>         com.srba.task.SysContextListener     </listener-class> </listener> 

第一種方法就愉快的搞完啦。
二、實現ApplicationListener<ContextRefreshedEvent>類

1.SrbaAutoTask類

 1 package com.srba.siss.rule.task; 2  3 import java.text.SimpleDateFormat; 4 import java.util.Date; 5 import java.util.Timer; 6 import java.util.TimerTask; 7  8 import javax.annotation.Resource; 9 10 import org.springframework.context.ApplicationListener;11 import org.springframework.context.event.ContextRefreshedEvent;12 import org.springframework.stereotype.Service;13 14 import com.srba.siss.rule.service.SrbaRuleTaskService;15 import com.srba.siss.rule.service.SystemCurrencyService;16 17 @Service18 public class SrbaAutoTask implements ApplicationListener<ContextRefreshedEvent>19 {    20     @Resource21     private SrbaRuleTaskService srbaRuleTaskService;22     @Override23     public void onApplicationEvent(ContextRefreshedEvent event) {24         // TODO Auto-generated method stub25         if(event.getApplicationContext().getParent() == null){26             System.out.println("+++++++++++++++++++++++++++系統每天調度任務已開啟,正在保護地球安全!++++++++++++++++++++++++++++");27             int i=1000;       //1000毫秒及1秒28             int s=1000*60*60; //每60分鐘執行一次29             Timer timer=new Timer();30             timer.schedule(new TimerAction(event), i, s);31         }32     }33 34     35 36 37 }

2.TimerAction()類,同一中的2。

3.配置applicationContext.xml 檔案,增加以下內容(tomcat啟動spring載入完成後,自動執行下面的類)

<!-- 自動掃描包com.srba.siss.rule.task,執行自動執行任務 -->    <context:component-scan base-package="com.srba.siss.rule.task"></context:component-scan>

 第二種調度方法也愉快的配置完了。

Timer中的schedule()方法是有多種重載格式的,以適應不同的情況。該方法的格式如下:
 void schedule(TimerTask task, Date time)
           安排在指定的時間執行指定的任務。
 void schedule(TimerTask task, Date firstTime, long period)
           安排指定的任務在指定的時間開始進行重複的固定順延強制。
 void schedule(TimerTask task, long delay)
           安排在指定延遲後執行指定的任務。
 void schedule(TimerTask task, long delay, long period)
           安排指定的任務從指定的延遲後開始進行重複的固定順延強制。
Timer是安全執行緒的,此類可擴充到大量同時安排的任務(存在數千個都沒有問題)。其所有構造方法都啟動計時器線程。可以調用cancel() 終止此計時器,丟棄所有當前已安排的任務。purge()從此計時器的任務隊列中移除所有已取消的任務。此類不提供即時保證:它使用 Object.wait(long) 方法來安排任務。
TimerTask是一個抽象類別,由 Timer 安排為一次執行或重複執行的任務。它有一個抽象方法run()----計時器任務要執行的操作。因此,每個具體的任務類都必須繼承TimerTask類,並且重寫run()方法。另外它還有兩個非抽象的方法:
 boolean cancel()
           取消此計時器任務。
 long scheduledExecutionTime()
           返回此任務最近實際 執行的安排 執行時間。

java web定時任務調度總結

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.