quartz(二)--與spring整合

    Quartz是一個強大的企業級任務調度框架,Spring中繼承並簡化了Quartz。上篇博客大概介紹了什麼是quartz,以及簡單的使用quartz,下面我們來看quartz如何與spring整合。


1.首先,準備jar包等;在web.xml文件中配置quartz使用的文件,配置在spring監聽下:

 

<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:applicationContext.xml
classpath:spring_quartz.xml
</param-value>
</context-param>


2.其次,編寫工作類:

public classQuartzJob
{
 
    public void work()
    {
       System.out.println("Hello World Quartz!!!");
    }
}

3.然後,編寫quartz配置文件,如下:

<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jee="http://www.springframework.org/schema/jee"
xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/jeehttp://www.springframework.org/schema/jee/spring-jee-2.0.xsd">
       <!-- 要調用的工作類 -->
        <bean id="quartzJob"class="quartz.QuartzJob"></bean>
       <!-- 定義調用對象和調用對象的方法 -->
        <bean id="jobtask"class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
            <!-- 調用的類 -->
            <propertyname="targetObject">
                <refbean="quartzJob"/>
            </property>
            <!-- 調用類中的方法 -->
            <propertyname="targetMethod">
                <value>work</value>
            </property>
        </bean>
       <!-- 定義觸發時間 -->
        <bean id="doTime"class="org.springframework.scheduling.quartz.CronTriggerBean">
            <propertyname="jobDetail">
                <refbean="jobtask"/>
            </property>
            <!-- cron表達式 -->
            <propertyname="cronExpression">
                <!-- 每隔5秒執行一次-->
                  <value>0/5 * * * *?</value>
               <!-- 每天20:30分執行-->
<!--                <value>0 30 20 ? **</value>-->
            </property>
        </bean>
       <!-- 總管理類 如果將lazy-init='false'那麼容器啓動就會執行調度程序 -->
        <bean id="startQuertz"lazy-init="false" autowire="no"class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
            <propertyname="triggers">
                <list>
                    <refbean="doTime"/>
                </list>
            </property>
        </bean>
</beans>


 

4.最後,配置文件設置爲每5秒執行一次,測試結果:


 

 

總結:

          quartz用起來很簡單:代碼簡單、配置少,不需要繼承一些東西,很靈活。同時,quartz很常用,很“靠譜”,功能也很強大:基於數據庫的調度、分佈式調度都能支持。技術是爲了解決其他技術無法或不便解決的問題,quartz很好的做到了這一點,讓任務調度變的很簡單。

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