spring2實現定時任務的一種方式

1. 在項目中放入Spring的jar包spring

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>中添加如下內容:app

    <context:annotation-config />
    <context:component-scan base-package="一個包路徑packagepath"></context:component-scan>
    <import resource="packagepath/spring2/scheduler.xml" />

       scheduler.xml的位置自定。spa

4. 配置scheduler.xml文件code

<?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含義以下:component

第一個bean,autoStartup用來設定定時任務是否自啓動,triggers用來設置有哪些定時任務。triggers的list中能夠放置多個<ref />,經過其餘bean的id做爲引用的標識。xml

第二個bean,jobDetail設置該定時任務要執行什麼操做,cronExpression設定定時策略。blog

第三個bean,targetObject和targetMethod分別設置定時任務由哪一個類和該類的方法來處理。其中的targetObject引用的是id爲testService的bean。concurrent表示是否併發,默認是true。get

相關文章
相關標籤/搜索