Spring中使用Schedule調度


  在spring中兩種辦法使用調度,以下使用是在spring4.0中。

  一、基於application配置文件,配置入下:

  

 1     <bean id="jobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
 2         <property name="targetObject" ref="businessObject" />
 3         <property name="targetMethod" value="invoke" />
 4         <property name="concurrent" value="false" />
 5     </bean>
 6     <bean id="Jobtrigger" class="org.springframework.scheduling.quartz.SimpleTriggerFactoryBean">
 7         <property name="jobDetail" ref="jobDetail" />
 8         <property name="startDelay" value="10000" />
 9         <property name="repeatInterval" value="3000" />
10     </bean>
11     <bean id="businessObject" class="com.aoshi.web.framework.im.polling.AutoSchedule"/>
12     <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
13         <property name="triggers">
14             <list>
15                 <ref bean="Jobtrigger"/>
16             </list>
17         </property>
18     </bean>

其中的businessObject類就是調用調度的類,代碼如下:

  

1 public class BusinessObject {
2 
3     int count=0;
4     public void invoke(){
5         System.out.println(getClass().getName()+"被調用了。。。"+(count++)+"次。");
6         
7     }
8 }

 

以上配置中targetMethod指定了調度的方法,concurrent設置是否並發執行。觸發器中 startDelay設置程序之前延遲,單位是毫秒。repeatInterval設置執行的間隔,單位是毫秒。最后配置的是調度工廠,指定觸發器。

 *這種方法需要quartz.jar 和quartz-jobs.jar包的支持。 

   二、基於spring注解實現調度

   使用spring注解來驅動調度,首先需要在spring配置文件中加入task命名空間,xmlns:task="http://www.springframework.org/schema/task"。接着加入調度注解掃描配置:

  <task:annotation-driven/>

  接着是寫注解的調度代碼:

  

 1 @Component
 2 public class AutoSchedule {
 3 
 4     private int count=0;
 5     
 6     @Scheduled(fixedDelay=5000)
 7     public void invoke(){
 8         System.out.println("被調用了:"+count++);
 9     }
10 }

@Scheduled注解的方法就會在程序啟動時候被自動執行,其中幾個常配置的參數,分別是

  fixedRate: 每一次執行調度方法的間隔,可以不用等上一次方法執行結束。可以理解為並發執行的。

  fixedDely: 兩次調度方法執行的間隔,它必須等上一次執行結束才會執行下一次。

  cro: 配置調度配置字符串。

其中配置字符串可以從properties文件中取得。例如:

  

1 @Scheduled(cron = "${cron.expression}")
2     public void demoServiceMethod()
3     {
4         System.out.println("Method executed at every 5 seconds. Current time is :: "+ new Date());
5     }

  在spring配置文件中引用配置文件:

  

1 <util:properties id="applicationProps" location="application.properties" />
2 <context:property-placeholder properties-ref="applicationProps" />

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM