spring2实现定时任务的一种方式

1. 在项目中放入Spring的jar包

2. applicationContext.xml的<beans xmlns>部分,添加context相关内容:

<beans xmlns=... ...

        xmlns:context="http://www.springframework.org/schema/context"

        xsi:schemaLocation="

                ... ...

                http://www.springframework.org/schema/context   

                http://www.springframework.org/schema/context/spring-context-2.5.xsd">



</beans>

3. 在<beans></beans>中添加以下内容:

    <context:annotation-config />

    <context:component-scan base-package="一个包路径packagepath"></context:component-scan>

    <import resource="packagepath/spring2/scheduler.xml" />

       scheduler.xml的位置自定。

4. 配置scheduler.xml文件

<?xml version="1.0" encoding="UTF-8"?>  

<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">  

<beans>   

    <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">       

        <property name="autoStartup" value="true" />    

        <property name="triggers">

            <list>   

                <ref local="mytrig"/>    

            </list>     

        </property>     

    </bean>   

    <bean id="mytrig" class="org.springframework.scheduling.quartz.CronTriggerBean">  

        <property name="jobDetail" ref="jd" />

        <property name="cronExpression">  

            <value>0 * * * * ?</value>

        </property>   

    </bean>   

    <bean id="jd" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">  

        <property name="targetObject" ref="testService"></property>     

        <property name="targetMethod" value="test"></property>     

        <property name="concurrent" value="false"/>    

    </bean>    

</beans>

自上而下的三个bean含义如下:

第一个bean,autoStartup用来设定定时任务是否自启动,triggers用来设置有哪些定时任务。triggers的list中可以放置多个<ref />,通过其他bean的id作为引用的标识。

第二个bean,jobDetail设置该定时任务要执行什么操作,cronExpression设定定时策略。

第三个bean,targetObject和targetMethod分别设置定时任务由哪个类和该类的方法来处理。其中的targetObject引用的是id为testService的bean。concurrent表示是否并发,默认是true。

 

你可能感兴趣的:(spring)