天天看點

spring定時器的兩種配置方式

 1、加入依賴包:

<dependency>
   <groupId>org.quartz-scheduler</groupId>
   <artifactId>quartz</artifactId>
   <version>2.2.1</version>
</dependency>
<dependency>
   <groupId>org.quartz-scheduler</groupId>
   <artifactId>quartz-jobs</artifactId>
   <version>2.2.1</version>
</dependency>      

 2、第一種方式:

寫一個方法,并在其上方加入@Scheduled注釋即可,如:

@Scheduled(cron = "0 0 0/2 * * ?")

 
  public void 
  test
  () {
       // do something
   }      

cron屬性解釋: http://www.cnblogs.com/jearay/p/3667906.html

3、第二種方式:

3.1、寫一個方法,如:

public class TestClass {

    /**
     * 定時器執行
     */
    public void execute() {
      //  do something ...
}      

 3.2、編寫spring-quartz.xml配置檔案,如:

<?xml version="1.0" ecodn="TF-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-4.0.xsd
        ">

    <!-- 要執行任務的任務類。 -->
    <bean id="quartzTest" class="com.service.TestClass">
    </bean>

    <bean id="quartzJob" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
        <property name="targetObject" ref="quartzTest"></property>
        <!-- 任務類中需要執行的方法 -->
        <property name="targetMethod" value="execute"></property>
        <!-- 上一次未執行完成的,要等待有再執行。 -->
        <property name="concurrent" value="false"></property>
    </bean>

    <bean id="testTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
        <property name="jobDetail" ref="quartzJob"/>
        <property name="cronExpression" value="0 0 12 * * ?"/>
    </bean>

    <bean id="schedulerFactoryBean" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
        <property name="triggers">
            <list>
                <ref bean="testTrigger"></ref>
            </list>
        </property>
    </bean>
</beans>      
最後将檔案spring-quartz.xml加載到spring配置檔案中即可!!!