1. 程式人生 > >java.util.Timer、Quartz與Spring task定時器任務的幾種實現方法

java.util.Timer、Quartz與Spring task定時器任務的幾種實現方法

轉載:https://www.jb51.net/article/106445.htm

一.分類

從實現的技術上來分類,目前主要有三種技術(或者說有三種產品):

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

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

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

從作業類的繼承方式來講,可以分為兩類:

1.作業類需要繼承自特定的作業類基類,如Quartz中需要繼承自org.springframework.scheduling.quartz.QuartzJobBean;java.util.Timer中需要繼承自java.util.TimerTask。

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

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

從任務排程的觸發時機來分,這裡主要是針對作業使用的觸發器,主要有以下兩種:

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

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

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

二.用法說明

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

Quartz

第一種,作業類繼承自特定的基類:org.springframework.scheduling.quartz.QuartzJobBean。

第一步:定義作業類

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

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

1

2

3

4

5

6

7

8

<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分鐘執行一次。

配置方式如下:

1

2

3

4

5

<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秒排程一次 -->

</bean>

第二種CronTriggerBean,支援到指定時間執行一次,如每天12:00執行一次等。

配置方式如下:

1

2

3

4

5

<bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">

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

<!—每天12:00執行一次 -->

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

</bean>

第四步:配置排程工廠

1

2

3

4

5

6

7

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

<property name="triggers">

<list>

<ref bean="cronTrigger" />

</list>

</property>

</bean>

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

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

第二種,作業類不繼承特定基類。

Spring能夠支援這種方式,歸功於兩個類:

1

2

3

org.springframework.scheduling.timer.MethodInvokingTimerTaskFactoryBean

 

org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean

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

第一步:編寫任務類

1

2

3

4

5

public class Job2 {

public void doJob2() {

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

}

}

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

第二步:配置作業類

1

2

3

4

5

6

7

8

<bean id="job2"

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

<property name="targetObject">

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

</property>

<property name="targetMethod" value="doJob2" />

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

</bean>

說明:這一步是關鍵步驟,宣告一個MethodInvokingJobDetailFactoryBean,有兩個關鍵屬性:targetObject指定任務類,targetMethod指定執行的方法。往下的步驟就與方法一相同了,為了完整,同樣貼出。

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

Quartz的作業觸發器有兩種,分別是

1

2

3

org.springframework.scheduling.quartz.SimpleTriggerBean

 

org.springframework.scheduling.quartz.CronTriggerBean

第一種SimpleTriggerBean,只支援按照一定頻度呼叫任務,如每隔30分鐘執行一次。

配置方式如下:

1

2

3

4

5

<bean id="simpleTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerBean">

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

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

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

</bean>

第二種CronTriggerBean,支援到指定時間執行一次,如每天12:00執行一次等。

配置方式如下:

1

2

3

4

5

<bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">

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

<!—每天12:00執行一次 -->

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

</bean>

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

第四步:配置排程工廠

1

2

3

4

5

6

7

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

<property name="triggers">

<list>

<ref bean="cronTrigger" />

</list>

</property>

</bean>

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

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

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

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

Spring-Task

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

形式,下面將分別介紹這兩種方式。

第一種:配置檔案方式

第一步:編寫作業類

即普通的pojo,如下: 

1

2

3

4

5

6

7

8

import org.springframework.stereotype.Service;

@Service

public class TaskJob {

  

 public void job1() {

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

 }

}

第二步:在spring配置檔案頭中新增名稱空間及描述

1

2

3

4

<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配置檔案中設定具體的任務

1

2

3

4

5

<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,我們看看原始檔中該註解的定義: 

1

2

3

4

5

6

7

8

9

10

11

@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

1

2

3

4

5

6

7

8

9

10

import org.springframework.scheduling.annotation.Scheduled;

import org.springframework.stereotype.Component;

 

@Component(“taskJob”)

public class TaskJob {

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

 public void job1() {

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

 }

}

第二步:新增task相關的配置: 

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

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

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

 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 />這句配置就可以了,這些引數都不是必須的。