定時任務(wù)

Spring + Quartz定時任務(wù)

第一種方法, 執(zhí)行任務(wù)的類繼承QuartzJobBean,Spring4.1.0版本后需要quartz2.X版本量蕊, Spring4.1.0之前需要quartz1.X版本骑歹。Spring4.1.0版本后+quartz2.X舉例:
  1. 執(zhí)行任務(wù)的類:
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;
import java.text.SimpleDateFormat;
import java.util.Date;

public class MySchedule extends QuartzJobBean {

    private int timeout;
    private static int INDEX = 0;

    @Override
    protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "第" + (++INDEX) + "次執(zhí)行MySchedule的定時任務(wù)");
    }

    public int getTimeout() {return timeout;}

    public void setTimeout(int timeout) {this.timeout = timeout;}
}
  1. applicationContext.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"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    
    <!-- 配置JobDetail -->
    <bean name="myScheduleJobDetail" class="org.springframework.scheduling.quartz.JobDetailFactoryBean">
        <property name="jobClass" value="com.quartz.myschedule.MySchedule" />
        <property name="jobDataAsMap">  
            <map>  
                <entry key="timeout" value="5" />  
            </map>  
        </property> 
    </bean>
    <!-- 配置觸發(fā)器 -->
    <!-- SimpleTriggerFactoryBean历葛,每隔多長時間執(zhí)行一次 -->
     <bean id="myScheduleJobTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerFactoryBean">
        <property name="jobDetail" ref="myScheduleJobDetail" />
        <!-- 延遲觸發(fā)時間价匠,延遲5秒進行觸發(fā) -->  
        <property name="startDelay" value="5000" />
        <!-- 重復(fù)觸發(fā)的時間間隔当纱,5秒 -->  
        <property name="repeatInterval" value="5000" />
    </bean>
    
    <!-- 配置ScheduleFactoryBean -->
    <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">  
        <property name="triggers">  
            <list>  
                <ref bean="myScheduleJobTrigger" />
            </list>  
        </property>  
    </bean> 
</beans>

注意1:配置觸發(fā)器的時候,有兩種方式霞怀。一種是每隔多長時間執(zhí)行一次(SimpleTriggerFactoryBean)惫东。一種是指定時間執(zhí)行(CronTriggerFactoryBean)莉给。當然毙石,第二種也可以通過配置表達式實現(xiàn)每隔多長時間執(zhí)行一次廉沮。如果需要第二種, 只需將上面applicationContext.xml中配置觸發(fā)器的代碼使用以下代碼替換即可

<bean id="myScheduleJobTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">  
        <property name="jobDetail" ref="myScheduleJobDetail" />  
        <!-- 每10秒運行一次 --> 
        <property name="cronExpression" value="0/10 * * * * ?" />  
    </bean> 

注意2:如果是低版本的spring和quartz徐矩, 將JobDetailFactoryBean改為JobDetailBean滞时。

3.web.xml中配置spring的監(jiān)聽

<!-- 配置Spring核心監(jiān)聽器 -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
  1. 啟動tomcat, 執(zhí)行定時任務(wù)滤灯。
  1. 可能出現(xiàn)錯誤:

如果使用高版本spring和低版本quartz:報錯坪稽。原因是 JobDetailFactoryBean的創(chuàng)建需要JobDetailImpl, 而低版本quartz1.X包下沒有該實現(xiàn)類鳞骤。

org.springframework.beans.factory.BeanCreationException: Error creating bean with name       'exampleJobDetail' defined in class path resource [applicationContext.xml]: Instantiation of bean failed; nested exception is java.lang.NoClassDefFoundError: org/quartz/impl/JobDetailImpl

如果使用低版本的spring和高版本的quartz:報錯窒百。原因是需要創(chuàng)建的JobDetailBean繼承了JobDetail, 而JobDetail是一個接口豫尽。

org.springframework.beans.factory.CannotLoadBeanClassException: Error loading class [org.springframework.scheduling.quartz.JobDetailBean] for bean with name 'exampleJobDetail' defined in class path resource [applicationContext.xml]: problem with class file or dependent class; nested exception is java.lang.IncompatibleClassChangeError: class org.springframework.scheduling.quartz.JobDetailBean has interface org.quartz.JobDetail as super class
第二種方法篙梢,執(zhí)行任務(wù)的類不用繼承其他超級類。這種方式可以實現(xiàn)低版本的spring(4.1.0)以前版本和高版本quartz(2.X)的結(jié)合使用美旧。 如果公司使用spring4.1.0以前版本渤滞,又不想使用quartz1.X版本, 可以通過這種方式榴嗅。但是使用較高版本spring(4.1.0以后)和低版本quartz結(jié)合妄呕, 報錯。
  1. 執(zhí)行任務(wù)的類
import java.text.SimpleDateFormat;
import java.util.Date;

public class MySchedule {

    private static int INDEX = 0;

    protected void myScheduleTask() {
        
        System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "第" + (++INDEX) + "次執(zhí)行MySchedule的定時任務(wù)");
   
    }
}
  1. applicationContext.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"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    
    <bean id="mySchedule" class="com.quartz.myschedule.MySchedule"></bean> 
    
    <!-- JobDetail任務(wù)調(diào)度 -->
    <bean id="myScheduleDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">  
        <!-- 指定任務(wù)類 -->  
        <property name="targetObject" ref="mySchedule" />  
        <!-- 指定任務(wù)執(zhí)行的方法 -->  
        <property name="targetMethod" value="myScheduleTask" />  
        
    </bean> 
    
    <!-- 觸發(fā)器 -->
    <bean id="myScheduleTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">  
        <property name="jobDetail" ref="myScheduleDetail" />  
        <!-- 每10秒運行一次 -->  
        <property name="cronExpression" value="0/3 * * * * ?" />  
    </bean>
    
    <!-- schedule工廠 -->
    <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">  
        <property name="triggers">  
            <list>  
                <ref bean="myScheduleTrigger" />  
            </list>  
        </property>  
    </bean> 
</beans>
  1. web.xml
<!-- 配置Spring核心監(jiān)聽器 -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
  1. 啟動tomcat嗽测, 執(zhí)行定時任務(wù)

Spring的定時任務(wù)

通過xml配置
  1. 執(zhí)行任務(wù)的類
import java.text.SimpleDateFormat;
import java.util.Date;

public class MySchedule {

    private static int INDEX = 0;

    public void myScheduleTask() {
        
        System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "第" + (++INDEX) + "次執(zhí)行MySchedule的定時任務(wù)");
   
    }
  1. applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:util="http://www.springframework.org/schema/util"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    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.2.xsd
           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
           http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
           http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
           http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd">

    <bean id="mySchedule" class="com.spring.task.MySchedule"></bean>
    <task:scheduled-tasks scheduler="scheduler">    
         <task:scheduled ref="mySchedule" method="myScheduleTask" cron="0/1 * * * * ?" />    
    </task:scheduled-tasks> 
    
    <task:scheduler id="scheduler" pool-size="10"/>
</beans>
  1. 啟動tomcat
第二種方式绪励,通過注解
  1. 執(zhí)行任務(wù)的類
import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class MySchedule {

    private static int INDEX = 0;

    @Scheduled(cron="0/1 * * * * ?")
    public void myScheduleTask() {
        
        System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "第" + (++INDEX) + "次執(zhí)行MySchedule的定時任務(wù)");
   
    }
}
  1. applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:util="http://www.springframework.org/schema/util"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    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.2.xsd
           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
           http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
           http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
           http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd">

    <context:component-scan base-package="com.spring.task"/>
    <task:annotation-driven scheduler="scheduler" mode="proxy"/>    
    <task:scheduler id="scheduler" pool-size="10"/>


</beans>
  1. 啟動tomcat測試。

jar包及詳細源碼:https://github.com/xueshimeng/schedule

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末唠粥,一起剝皮案震驚了整個濱河市优炬,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌厅贪,老刑警劉巖蠢护,帶你破解...
    沈念sama閱讀 221,635評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異养涮,居然都是意外死亡葵硕,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,543評論 3 399
  • 文/潘曉璐 我一進店門贯吓,熙熙樓的掌柜王于貴愁眉苦臉地迎上來懈凹,“玉大人,你說我怎么就攤上這事悄谐〗槠溃” “怎么了?”我有些...
    開封第一講書人閱讀 168,083評論 0 360
  • 文/不壞的土叔 我叫張陵,是天一觀的道長们陆。 經(jīng)常有香客問我寒瓦,道長,這世上最難降的妖魔是什么坪仇? 我笑而不...
    開封第一講書人閱讀 59,640評論 1 296
  • 正文 為了忘掉前任杂腰,我火速辦了婚禮,結(jié)果婚禮上椅文,老公的妹妹穿的比我還像新娘喂很。我一直安慰自己,他們只是感情好皆刺,可當我...
    茶點故事閱讀 68,640評論 6 397
  • 文/花漫 我一把揭開白布少辣。 她就那樣靜靜地躺著,像睡著了一般羡蛾。 火紅的嫁衣襯著肌膚如雪毒坛。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 52,262評論 1 308
  • 那天林说,我揣著相機與錄音煎殷,去河邊找鬼。 笑死腿箩,一個胖子當著我的面吹牛豪直,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播珠移,決...
    沈念sama閱讀 40,833評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼弓乙,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了钧惧?” 一聲冷哼從身側(cè)響起暇韧,我...
    開封第一講書人閱讀 39,736評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎浓瞪,沒想到半個月后懈玻,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,280評論 1 319
  • 正文 獨居荒郊野嶺守林人離奇死亡乾颁,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,369評論 3 340
  • 正文 我和宋清朗相戀三年涂乌,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片英岭。...
    茶點故事閱讀 40,503評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡湾盒,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出诅妹,到底是詐尸還是另有隱情罚勾,我是刑警寧澤,帶...
    沈念sama閱讀 36,185評論 5 350
  • 正文 年R本政府宣布,位于F島的核電站尖殃,受9級特大地震影響丈莺,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜分衫,卻給世界環(huán)境...
    茶點故事閱讀 41,870評論 3 333
  • 文/蒙蒙 一场刑、第九天 我趴在偏房一處隱蔽的房頂上張望般此。 院中可真熱鬧蚪战,春花似錦、人聲如沸铐懊。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,340評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽科乎。三九已至壁畸,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間茅茂,已是汗流浹背捏萍。 一陣腳步聲響...
    開封第一講書人閱讀 33,460評論 1 272
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留空闲,地道東北人令杈。 一個月前我還...
    沈念sama閱讀 48,909評論 3 376
  • 正文 我出身青樓,卻偏偏與公主長得像碴倾,于是被迫代替她去往敵國和親逗噩。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 45,512評論 2 359

推薦閱讀更多精彩內(nèi)容