Spring整合 Quartz 以及 Quartz動態任務


一、Quartz內部原理
    https://www.cnblogs.com/zhangchengzhangtuo/p/5705672.html
二、Quartz常用API
   1,Job接口
     需要我自己去實現
   2,JobDetail
     提供一些監聽,主要易於擴展
   3,Trigger 觸發器
     可以認爲是具體的執行方法,具體要做什麼事情
   4,Calendar
     記錄所有的任務觸發點
   5,Scheduler 調度器
      獨立的運行容器,所有的任務相關的東西全部放在調度器裏面
   6,SchedulerFactory是Spring給我們提供的一個入口

   表達式
   CronExpression 表達式格式如下(有嚴格的順序):
   秒  分  時  日  月  周  年
   https://www.cnblogs.com/pipi-changing/p/5697481.html
   https://www.cnblogs.com/linjiqin/archive/2013/07/08/3178452.html
   CronExpression參考了linux的cron,比windows裏面的計劃任務實際更加詳細




三、xml配置方式添加Quartz
  spring對應的配置文件如下:
  <bean id = "xmlTimer" class = "XMLTimer" />
  <bean id="xmlInvoker" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
      <property name="targetObject" ref="xmlTimer"/>
      <property name="targetMethod" value="execute"/>
  </bean>
  <bean id="xmlTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
    <property name="jobDetail" ref="xmlInvoker"/>
    <property name="cronExpression" value="0/5 * * * * ?"/>
  </bean>
  <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
    <property name="triggers">
      <list>
        <ref bean="xmlTrigger"></ref>
      </list>
    </property>
  </bean>

  對應的class:
  public class XMLTimer{
     public execute(){
        System.out.println("execute....");
     }
  }
四、Annotation方式添加Quartz

   http://jingyemingyue.iteye.com/blog/1202292
   1,xml中引入命名空間
     xmlns:task="http://www.springframework.org/schema/task"
     然後添加<task:annotation-driven/>
   2,java代碼
       @Component
       public class AnnotationQuartz {
          //需要注意@Scheduled這個註解,它可配置多個屬性:cron\fixedDelay\fixedRate
          @Scheduled(cron="0,10,20,30,40,50 * * * * ?")
          public void test(){
             System.out.println("0.0");
          }
       }


 Spring任務的動態調度:
 可以參考:https://www.cnblogs.com/hehejava/p/4727205.html
 實現思路:
 1,由於SchedulerFactoryBean中管理了所有調度器,我們可以從spring容器中拿到SchedulerFactoryBean

       @Resource(name="scheduler")
       private Scheduler scheduler;
 2,創建任務
    ........

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