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很好的做到了这一点,让任务调度变的很简单。

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