天天看點

定時任務

spring定時任務的幾種實作

近日項目開發中需要執行一些定時任務,比如需要在每天淩晨時候,分析一次前一天的日志資訊,借此機會整理了一下定時任務的幾種實作方式,由于項目采用spring架構,是以我都将結合

spring架構來介紹。

java自帶的java.util.timer類,這個類允許你排程一個java.util.timertask任務。使用這種方式可以讓你的程式按照某一個頻度執行,但不能在指定時間運作。一般用的較少,這篇文章将不做詳細介紹。

使用quartz,這是一個功能比較強大的的排程器,可以讓你的程式在指定時間執行,也可以按照某一個頻度執行,配置起來稍顯複雜,稍後會詳細介紹。

spring3.0以後自帶的task,可以将它看成一個輕量級的quartz,而且使用起來比quartz簡單許多,稍後會介紹。

作業類需要繼承自特定的作業類基類,如quartz中需要繼承自org.springframework.scheduling.quartz.quartzjobbean;java.util.timer中需要繼承自java.util.timertask。

作業類即普通的java類,不需要繼承自任何基類。

注:個人推薦使用第二種方式,因為這樣是以的類都是普通類,不需要事先差別對待。

每隔指定時間則觸發一次,在quartz中對應的觸發器為:org.springframework.scheduling.quartz.simpletriggerbean

每到指定時間則觸發一次,在quartz中對應的排程器為:org.springframework.scheduling.quartz.crontriggerbean

注:并非每種任務都可以使用這兩種觸發器,如java.util.timertask任務就隻能使用第一種。quartz和spring task都可以支援這兩種觸發條件。

詳細介紹每種任務排程工具的使用方式,包括quartz和spring task兩種。

第一步:定義作業類

java代碼  

定時任務

import org.quartz.jobexecutioncontext;  

import org.quartz.jobexecutionexception;  

import org.springframework.scheduling.quartz.quartzjobbean;  

public class job1 extends quartzjobbean {  

private int timeout;  

private static int i = 0;  

//排程工廠執行個體化後,經過timeout時間開始執行排程  

public void settimeout(int timeout) {  

this.timeout = timeout;  

}  

/** 

* 要排程的具體任務 

*/  

@override  

protected void executeinternal(jobexecutioncontext context)  

throws jobexecutionexception {  

  system.out.println("定時任務執行中…");  

 第二步:spring配置檔案中配置作業類jobdetailbean

xml代碼  

定時任務

<bean name="job1" class="org.springframework.scheduling.quartz.jobdetailbean">  

<property name="jobclass" value="com.gy.job1" />  

<property name="jobdataasmap">  

<map>  

<entry key="timeout" value="0" />  

</map>  

</property>  

</bean>  

 說明:org.springframework.scheduling.quartz.jobdetailbean有兩個屬性,jobclass屬性即我們在java代碼中定義的任務類,jobdataasmap屬性即該任務類中需要注入的屬性值。

第三步:配置作業排程的觸發方式(觸發器)

quartz的作業觸發器有兩種,分别是

org.springframework.scheduling.quartz.simpletriggerbean

org.springframework.scheduling.quartz.crontriggerbean

第一種simpletriggerbean,隻支援按照一定頻度調用任務,如每隔30分鐘運作一次。

配置方式如下:

定時任務

<bean id="simpletrigger" class="org.springframework.scheduling.quartz.simpletriggerbean">  

<property name="jobdetail" ref="job1" />  

<property name="startdelay" value="0" /><!-- 排程工廠執行個體化後,經過0秒開始執行排程 -->  

<property name="repeatinterval" value="2000" /><!-- 每2秒排程一次 -->  

第二種crontriggerbean,支援到指定時間運作一次,如每天12:00運作一次等。

定時任務

<bean id="crontrigger" class="org.springframework.scheduling.quartz.crontriggerbean">  

<!—每天12:00運作一次 -->  

<property name="cronexpression" value="0 0 12 * * ?" />  

 關于cronexpression表達式的文法參見附錄。

第四步:配置排程工廠 

定時任務

<bean class="org.springframework.scheduling.quartz.schedulerfactorybean">  

<property name="triggers">  

<list>  

<ref bean="crontrigger" />  

</list>  

 說明:該參數指定的就是之前配置的觸發器的名字。

第五步:啟動你的應用即可,即将工程部署至tomcat或其他容器。

spring能夠支援這種方式,歸功于兩個類:

org.springframework.scheduling.timer.methodinvokingtimertaskfactorybean

org.springframework.scheduling.quartz.methodinvokingjobdetailfactorybean

這兩個類分别對應spring支援的兩種實作任務排程的方式,即前文提到到java自帶的timer task方式和quartz方式。這裡我隻寫methodinvokingjobdetailfactorybean的用法,使用該類的好處是,我們的任務類不再需要繼承自任何類,而是普通的pojo。

第一步:編寫任務類

定時任務

public class job2 {  

public void dojob2() {  

system.out.println("不繼承quartzjobbean方式-排程進行中...");  

 可以看出,這就是一個普通的類,并且有一個方法。

第二步:配置作業類

定時任務

<bean id="job2"  

class="org.springframework.scheduling.quartz.methodinvokingjobdetailfactorybean">  

<property name="targetobject">  

<bean class="com.gy.job2" />  

<property name="targetmethod" value="dojob2" />  

<property name="concurrent" value="false" /><!-- 作業不并發排程 -->  

 說明:這一步是關鍵步驟,聲明一個methodinvokingjobdetailfactorybean,有兩個關鍵屬性:targetobject指定任務類,targetmethod指定運作的方法。往下的步驟就與方法一相同了,為了完整,同樣貼出。

定時任務

<property name="jobdetail" ref="job2" />  

 第二種crontriggerbean,支援到指定時間運作一次,如每天12:00運作一次等。

定時任務

以上兩種排程方式根據實際情況,任選一種即可。

定時任務

說明:該參數指定的就是之前配置的觸發器的名字。

到此,spring中quartz的基本配置就介紹完了,當然了,使用之前,要導入相應的spring的包與quartz的包,這些就不消多說了。

其實可以看出quartz的配置看上去還是挺複雜的,沒有辦法,因為quartz其實是個重量級的工具,如果我們隻是想簡單的執行幾個簡單的定時任務,有沒有更簡單的工具,有!

請看我第下文spring task的介紹。

上節介紹了在spring 中使用quartz,本文介紹spring3.0以後自主開發的定時任務工具,spring task,可以将它比作一個輕量級的quartz,而且使用起來很簡單,除spring相關的包外不需要額外的包,而且支援注解和配置檔案兩種

形式,下面将分别介紹這兩種方式。

第一步:編寫作業類

即普通的pojo,如下:

定時任務

import org.springframework.stereotype.service;  

@service  

public class taskjob {  

    public void job1() {  

        system.out.println(“任務進行中。。。”);  

    }  

 第二步:在spring配置檔案頭中添加命名空間及描述

定時任務

<beans xmlns="http://www.springframework.org/schema/beans"  

    xmlns:task="http://www.springframework.org/schema/task"   

    。。。。。。  

    xsi:schemalocation="http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd">  

 第三步:spring配置檔案中設定具體的任務

定時任務

 <task:scheduled-tasks>   

        <task:scheduled ref="taskjob" method="job1" cron="0 * * * * ?"/>   

</task:scheduled-tasks>  

<context:component-scan base-package=" com.gy.mytask " />  

說明:ref參數指定的即任務類,method指定的即需要運作的方法,cron及cronexpression表達式,具體寫法這裡不介紹了,詳情見上篇文章附錄。

<context:component-scan base-package="com.gy.mytask" />這個配置不消多說了,spring掃描注解用的。

到這裡配置就完成了,是不是很簡單。

也許我們不想每寫一個任務類還要在xml檔案中配置下,我們可以使用注解@scheduled,我們看看源檔案中該注解的定義:

定時任務

@target({java.lang.annotation.elementtype.method, java.lang.annotation.elementtype.annotation_type})  

@retention(retentionpolicy.runtime)  

@documented  

public @interface scheduled  

{  

  public abstract string cron();  

  public abstract long fixeddelay();  

  public abstract long fixedrate();  

 可以看出該注解有三個方法或者叫參數,分别表示的意思是:

cron:指定cron表達式

fixeddelay:官方文檔解釋:an interval-based trigger where the interval is measured from the completion time of the previous task. the time unit value is measured in milliseconds.即表示從上一個任務完成開始到下一個任務開始的間隔,機關是毫秒。

fixedrate:官方文檔解釋:an interval-based trigger where the interval is measured from the start time of the previous task. the time unit value is measured in milliseconds.即從上一個任務開始到下一個任務開始的間隔,機關是毫秒。

下面我來配置一下。

第一步:編寫pojo

定時任務

import org.springframework.scheduling.annotation.scheduled;    

import org.springframework.stereotype.component;  

@component(“taskjob”)  

    @scheduled(cron = "0 0 3 * * ?")  

 第二步:添加task相關的配置:

定時任務

<?xml version="1.0" encoding="utf-8"?>  

    xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xmlns:aop="http://www.springframework.org/schema/aop"  

    xmlns:context="http://www.springframework.org/schema/context"  

    xmlns:tx="http://www.springframework.org/schema/tx"  

    xmlns:task="http://www.springframework.org/schema/task"  

    xsi:schemalocation="  

        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  

        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd  

        http://www.springframework.org/schema/context   

http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd  

        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd  

        http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd"  

    default-lazy-init="false">  

    <context:annotation-config />  

    <!—spring掃描注解的配置   -->  

    <context:component-scan base-package="com.gy.mytask" />  

<!—開啟這個配置,spring才能識别@scheduled注解   -->  

    <task:annotation-driven scheduler="qbscheduler" mode="proxy"/>  

    <task:scheduler id="qbscheduler" pool-size="10"/>  

說明:理論上隻需要加上<task:annotation-driven />這句配置就可以了,這些參數都不是必須的。

 ok配置完畢,當然spring task還有很多參數,我就不一一解釋了,具體參考xsd文檔http://www.springframework.org/schema/task/spring-task-3.0.xsd。

附錄:

cronexpression的配置說明,具體使用以及參數請百度google

字段   允許值   允許的特殊字元

秒    0-59    , - * /

分    0-59    , - * /

小時    0-23    , - * /

日期    1-31    , - * ? / l w c

月份    1-12 或者 jan-dec    , - * /

星期    1-7 或者 sun-sat    , - * ? / l c #

年(可選)    留白, 1970-2099    , - * / 

- 區間  

* 通配符  

? 你不想設定那個字段

下面隻例出幾個式子

cron表達式    含義 

"0 0 12 * * ?"    每天中午十二點觸發 

"0 15 10 ? * *"    每天早上10:15觸發 

"0 15 10 * * ?"    每天早上10:15觸發 

"0 15 10 * * ? *"    每天早上10:15觸發 

"0 15 10 * * ? 2005"    2005年的每天早上10:15觸發 

"0 * 14 * * ?"    每天從下午2點開始到2點59分每分鐘一次觸發 

"0 0/5 14 * * ?"    每天從下午2點開始到2:55分結束每5分鐘一次觸發 

"0 0/5 14,18 * * ?"    每天的下午2點至2:55和6點至6點55分兩個時間段内每5分鐘一次觸發 

"0 0-5 14 * * ?"    每天14:00至14:05每分鐘一次觸發 

"0 10,44 14 ? 3 wed"    三月的每周三的14:10和14:44觸發 

"0 15 10 ? * mon-fri"    每個周一、周二、周三、周四、周五的10:15觸發