spring-task簡單實用小結

spring-task,是spring 3.0以後自帶的定時任務工作機制,可以將它看成一個輕量級的Quartz,使用起來比Quartz簡單的多,並且不需要引用額外的jar包

首先編寫我們的任務類,就是普通的java類,不用繼承或實現其它類

並且增加如下spring 配置信息
<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:task="http://www.springframework.org/schema/task"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
        http://www.springframework.org/schema/fex
        http://www.springframework.org/schema/fex/spring-fex-1.5.xsd
        http://www.springframework.org/schema/task 
        http://www.springframework.org/schema/task/spring-task-3.1.xsd 
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.1.xsd"
        >

	<!-- 定時任務聲明 -->

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

	<task:annotation-driven executor="executor" scheduler="scheduler" />
	<!-- Spring定時器註解開關-->  
  <!--   <task:annotation-driven />   -->
    <!-- 此處對於定時時間的配置會被註解中的時間配置覆蓋,因此,如需要配置就不要再使用註解 -->  
    <task:scheduled-tasks scheduler="scheduler">  
    	<!-- 每天晚上1點執行 -->
<span style="white-space:pre">	</span><!-- ref對應的是任務類的註解名稱  method對應執行任務的方法 -->
        <task:scheduled ref="testTask" method="testTaskMethod" cron="0 0 1 * * ?"/>  
    </task:scheduled-tasks>  
	

	<!-- 定時任務掃描的目錄 -->
	<context:component-scan base-package="com.test.task" />

如上配置,配置文件如果定義了任務的執行時間,則不需要通過註解的方式在代碼中定義,詳見代碼中16行註釋部分。
如果完全使用註解的話則可以去掉
<task:scheduled-tasks scheduler="scheduler"> 該部分配置



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章