在Spring中使用JDK定時器實現調度任務

來源:互聯網
上載者:User
在Spring中使用JDK定時器實現調度任務

作者:chszs,轉載需註明。部落客頁:http://blog.csdn.net/chszs

本文探討Spring如何整合JDK的Timer定時器,實現計劃執行任務。

有時候,需要執行一些無使用者互動的程式,就像在指定的時間間隔後台運行進程那樣。比如,殺毒軟體可以每隔2天就在後台運行一次。又比如某些程式每天都要串連一次伺服器,查看有沒有更新。

本文探討Spring如何整合JDK的Timer定時器,實現計劃執行任務。

一、Spring框架組成JDK的Timer

JDK的Timer任務對象提供了在指定時間執行任何任務的功能。我們來看下面的例子:

假設我們想寫一個服務,此服務周期性的檢查互連網串連,並用日誌記錄串連的狀態。讓我們假定此服務是全天候啟動並執行,且每隔30秒執行一次。

所需要的JAR包如下:

log4j-1.2.13.jar
commons-logging-1.1.1.jar
spring-beans-3.2.4.RELEASE.jar
spring-context-3.2.4.RELEASE.jar
spring-context-support-3.2.4.RELEASE.jar
spring-core-3.2.4.RELEASE.jar
spring-expression-3.2.4.RELEASE.jar

二、寫服務類

下面的類實現了互連網串連檢查。

Listing 1: CheckInternetConnectionService.java

package com.chszs;import java.net.URL;import java.net.URLConnection;import java.util.Date;public class CheckInternetConnectionService {public void checkConnection(){if(doCheck()){System.out.println(new Date() + "Internet connection available");}else{System.out.println(new Date() + "Internet connection not available");}}private boolean doCheck(){URL urlObject = null;URLConnection urlConnection = null;try{urlObject = new URL("http://www.baidu.com");urlConnection = urlObject.openConnection();urlConnection.getContent();return true;}catch(Exception e){return false;}}}

上面的代碼很簡單,doCheck()方法檢查互連網串連是否有效。

三、封裝定時器任務服務

下面我們寫一個服務,實現定時任務。代碼如下:

Listing 2: CheckInternetConnectionWithTimerTask

package com.chszs;import java.util.TimerTask;public class CheckInternetConnectionWithTimerTask extends TimerTask{private CheckInternetConnectionService service;public CheckInternetConnectionService getService(){return service;}public void setService(CheckInternetConnectionService service){this.service = service;}@Overridepublic void run() {service.checkConnection();}}

此類繼承了java.util.TimerTask類。

重寫了run()方法,可以執行任意操作。這裡是調用互連網串連檢查。

注意定時器任務依賴於串連服務物件。稍後,我們將看到怎樣連線這兩個對象。

四、配置

至今,我們還沒有指定執行的時間間隔。Spring提供了這樣的配置支援。下面我們來看看該如何配置:

Listing 3: timer.xml

<?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:context="http://www.springframework.org/schema/context"xmlns:cache="http://www.springframework.org/schema/cache" xmlns:p="http://www.springframework.org/schema/p"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.0.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-3.0.xsd"><bean id="connectionCheckService" class="com.chszs.CheckInternetConnectionService"></bean><bean id="connectionCheckTimerTask" class="com.chszs.CheckInternetConnectionWithTimerTask"><property name="service" ref="connectionCheckService" /></bean><bean id="scheduledConnectionCheckTimerTask" class="org.springframework.scheduling.timer.ScheduledTimerTask"><property name="delay" value="2000" /><property name="period" value="30000" /><property name="timerTask" ref="connectionCheckTimerTask" /></bean><bean class="org.springframework.scheduling.timer.TimerFactoryBean"><property name="scheduledTimerTasks"><list><ref bean="scheduledConnectionCheckTimerTask" /></list></property></bean></beans>

以上設定檔的細節:

"connectionCheckService"這個Bean表示互連網串連服務。

"connectionCheckTimerTask"這個Bean定義了定時器任務。由於此定時器任務依賴於"connectionCheckService"這個Bean,故通過配置進行注入。

下面的代碼是從Spring架構中聲明定時器任務的調度對象:

<bean id="scheduledConnectionCheckTimerTask" class="org.springframework.scheduling.timer.ScheduledTimerTask"><property name="delay" value="2000" /><property name="period" value="30000" /><property name="timerTask" ref="connectionCheckTimerTask" /></bean>

org.springframework.scheduling.timer.ScheduledTimerTask這個類提供了對定時任務調度執行的支援。

屬性delay的單位是毫秒,它指定任務執行前需要延時多少時間。2000意味著延時2秒開始執行任務。

第二個屬性period的單位也是毫秒,它表示任務每隔多少時間就重複執行一次。30000這個值表示每隔30秒執行一次。

最後一個屬性是timerTask,它指定實際要執行的任務。

觸發調度任務是通過TimerFactoryBean進行的。它可以指定待調度的任務對象列表,儘管這裡只有1個待調度的任務對象。

<bean class="org.springframework.scheduling.timer.TimerFactoryBean"><property name="scheduledTimerTasks"><list><ref bean="scheduledConnectionCheckTimerTask" /></list></property></bean>

五、用戶端

用戶端程式會載入應用程式的上下文。一旦上下文被載入,服務物件、定時器任務對象、調度的定時器任務對象都會被載入並連線。下面我們繼續介紹觸發器Bean是如何觸發定時器任務的執行,互連網串連在每隔30秒運行一次。

Listing 4: Client.java

package com.chszs;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class Client {public static void main(String[] args){ApplicationContext ctx = new ClassPathXmlApplicationContext("timer.xml");}}

運行Client.java,可以看到每隔30秒定時器任務就調度執行一次。
執行結果如下:

Sun Aug 11 21:08:26 CST 2013Internet connection availableSun Aug 11 21:08:56 CST 2013Internet connection availableSun Aug 11 21:09:26 CST 2013Internet connection availableSun Aug 11 21:09:56 CST 2013Internet connection available

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.