<kbd id="afajh"><form id="afajh"></form></kbd>
<strong id="afajh"><dl id="afajh"></dl></strong>
    <del id="afajh"><form id="afajh"></form></del>
        1. <th id="afajh"><progress id="afajh"></progress></th>
          <b id="afajh"><abbr id="afajh"></abbr></b>
          <th id="afajh"><progress id="afajh"></progress></th>

          SpringBoot整合Quartz調(diào)度框架實現(xiàn)任務調(diào)度(附學習源碼)

          共 13865字,需瀏覽 28分鐘

           ·

          2021-03-24 12:00

          點擊上方藍色“小哈學Java”,選擇“設(shè)為星標

          回復“資源”獲取獨家整理的學習資料!

          來源gyoomi.blog.csdn.net/article/details/83382000

          一、引言

          定時任務調(diào)度是Java開發(fā)中不可或缺的重要部分,但是Java自帶的Time等任務調(diào)度類在實際項目中不好用。所以Quartz和Spring Task就成了我們項目開發(fā)技術(shù)選型最多的,在這里我們著重探討一下Quartz在Spring Boot 2.X版本中的使用。

          二、Quartz

          1. 介紹

          Quartz是OpenSymphony開源組織在Job scheduling領(lǐng)域的開源項目,它可以與J2EE與J2SE應用程序相結(jié)合也可以單獨使用。Quartz可以用來創(chuàng)建簡單或為運行十個,百個,甚至是好幾萬個Jobs這樣復雜的日程序表。Jobs可以做成標準的Java組件或 EJBs。

          Quartz是一個任務日程管理系統(tǒng),一個在預先確定(被納入日程)的時間到達時,負責執(zhí)行(或者通知)其他軟件組件的系統(tǒng)。

          Quartz用一個小Java庫發(fā)布文件(.jar文件),這個庫文件包含了所有Quartz核心功能。這些功能的主要接口(API)是Scheduler接口。它提供了簡單的操作,例如:將任務納入日程或者從日程中取消,開始/停止/暫停日程進度。

          2.安裝配置

          官方網(wǎng)站:

          http://quartz-scheduler.org/

          3.設(shè)計架構(gòu)

          介紹

          • Scheduler – 核心調(diào)度器
          • Job – 任務
          • JobDetail – 任務描述
          • Trigger – 觸發(fā)器

          圖示

          多個定時的圖示如下:

          對比下配置xml中的配置:

          <?xml version="1.0" encoding="UTF-8"?>
          <beans xmlns="http://www.springframework.org/schema/beans"
              xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
              xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
              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
              http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
              http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
              http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd"
          >


              <!-- 
                  Spring整合Quartz進行配置遵循下面的步驟:
                  1:定義工作任務的Job
                  2:定義觸發(fā)器Trigger,并將觸發(fā)器與工作任務綁定
                  3:定義調(diào)度器,并將Trigger注冊到Scheduler
               -->

              <!-- 1:定義任務的bean ,這里使用JobDetailFactoryBean,也可以使用MethodInvokingJobDetailFactoryBean ,配置類似-->
              <bean name="hwJob" class="org.springframework.scheduling.quartz.JobDetailFactoryBean">
                  <!-- 指定job的名稱 -->
                  <property name="name" value="hw_job"/>
                  <!-- 指定job的分組 -->
                  <property name="group" value="hw_group"/>
                  <!-- 指定具體的job類 -->
                  <property name="jobClass" value="com.dufy.spring.quartz.chapter01.job.HelloWorldJob"/>
                  <!-- 必須設(shè)置為true,如果為false,當沒有活動的觸發(fā)器與之關(guān)聯(lián)時會在調(diào)度器中會刪除該任務  -->
                  <property name="durability" value="true"/>
                  <!-- 指定spring容器的key,如果不設(shè)定在job中的jobmap中是獲取不到spring容器的 -->
                  <property name="applicationContextJobDataKey" value="applicationContext"/>
              </bean>
              <!-- 2.1:定義觸發(fā)器的bean,定義一個Simple的Trigger,一個觸發(fā)器只能和一個任務進行綁定 -->
              <!-- <bean name="simpleTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerFactoryBean">
                  指定Trigger的名稱
                  <property name="name" value="hw_trigger"/>
                  指定Trigger的名稱
                  <property name="group" value="hw_trigger_group"/>
                  指定Tirgger綁定的Job
                  <property name="jobDetail" ref="hwJob"/>
                  指定Trigger的延遲時間 1s后運行
                  <property name="startDelay" value="1000"/>
                  指定Trigger的重復間隔  5s
                  <property name="repeatInterval" value="5000"/>
                  指定Trigger的重復次數(shù)
                  <property name="repeatCount" value="5"/>
              </bean> -->


              <!-- 2.2:定義觸發(fā)器的bean,定義一個Cron的Trigger,一個觸發(fā)器只能和一個任務進行綁定 -->
              <bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
                  <!-- 指定Trigger的名稱 -->
                  <property name="name" value="hw_trigger"/>
                  <!-- 指定Trigger的名稱 -->
                  <property name="group" value="hw_trigger_group"/>
                  <!-- 指定Tirgger綁定的Job -->
                  <property name="jobDetail" ref="hwJob"/>
                  <!-- 指定Cron 的表達式 ,當前是每隔1s運行一次 -->
                  <property name="cronExpression" value="0/1 * * * * ?" />
              </bean>


              <!-- 3.定義調(diào)度器,并將Trigger注冊到調(diào)度器中 -->
              <bean id="scheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
                  <property name="triggers">
                      <list>
                          <!-- <ref bean="simpleTrigger"/> -->
                          <ref bean="cronTrigger"/>
                      </list>
                  </property>
                  <!-- <property name="autoStartup" value="true" /> -->
              </bean>

          </beans>

          三、整合

          1.項目基礎(chǔ)

          項目是基于Spring Boot2.x版本的。

          2.添加依賴

          <!-- quartz依賴 -->
          <dependency>
              <groupId>org.springframework.boot</groupId>
              <artifactId>spring-boot-starter-quartz</artifactId>
          </dependency>

          3.yml配置

          application-quartz.yml的配置內(nèi)容如下

          spring:
            quartz:
              #相關(guān)屬性配置
              properties:
                org:
                  quartz:
                    scheduler:
                      instanceName: clusteredScheduler
                      instanceId: AUTO
                    jobStore:
                      class: org.quartz.impl.jdbcjobstore.JobStoreTX
                      driverDelegateClass: org.quartz.impl.jdbcjobstore.StdJDBCDelegate
                      tablePrefix: QRTZ_
                      isClustered: true
                      clusterCheckinInterval: 10000
                      useProperties: false
                    threadPool:
                      class: org.quartz.simpl.SimpleThreadPool
                      threadCount: 10
                      threadPriority: 5
                      threadsInheritContextClassLoaderOfInitializingThread: true
              #數(shù)據(jù)庫方式
              job-store-type: jdbc
              #初始化表結(jié)構(gòu)
              #jdbc:
                #initialize-schema: never

          4.創(chuàng)建任務測試類

          簡單任務

          代碼如下:

          public class MyJob extends QuartzJobBean {

              @Override
              protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
                  System.out.println("start My Job:" + LocalDateTime.now());
                  try {
                      Thread.sleep(3000);
                  } catch (InterruptedException e) {
                      e.printStackTrace();
                  }
                  System.out.println("end My Job:" + LocalDateTime.now());

              }
          }

          CRON任務

          public class MyCronJob extends QuartzJobBean {

              @Autowired
              IndexController indexController;

              @Override
              protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
                  System.out.println("任務執(zhí)行了" + new Date());
                  // indexController.testMail();
              }
          }

          5.Java配置(QuartzConfiguration)

          @Configuration
          public class QuartzConfiguration {

           // 使用jobDetail包裝job
              @Bean
              public JobDetail myJobDetail() {
                  return JobBuilder.newJob(MyJob.class).withIdentity("myJob").storeDurably().build();
              }

           // 把jobDetail注冊到trigger上去
              @Bean
              public Trigger myJobTrigger() {
                  SimpleScheduleBuilder scheduleBuilder = SimpleScheduleBuilder.simpleSchedule()
                          .withIntervalInSeconds(15).repeatForever();

                  return TriggerBuilder.newTrigger()
                          .forJob(myJobDetail())
                          .withIdentity("myJobTrigger")
                          .withSchedule(scheduleBuilder)
                          .build();
              }

           // 使用jobDetail包裝job
              @Bean
              public JobDetail myCronJobDetail() {
                  return JobBuilder.newJob(MyCronJob.class).withIdentity("myCronJob").storeDurably().build();
              }

           // 把jobDetail注冊到Cron表達式的trigger上去
              @Bean
              public Trigger CronJobTrigger() {
                  CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule("0/10 * * * * ?");

                  return TriggerBuilder.newTrigger()
                          .forJob(myCronJobDetail())
                          .withIdentity("myCronJobTrigger")
                          .withSchedule(cronScheduleBuilder)
                          .build();
              }
          }

          其實上面的配置就等價于在傳統(tǒng)的xml中配置bean是一樣的。

          6.啟動測試

          至此,SpringBoot集成Quartz的完畢。

          四、總結(jié)

          Spring Boot集成quartz還是比較簡單的。

          其實還有更高級的用法,就是前臺動態(tài)創(chuàng)建和控制定時任務,后面有時間再完善。大家先把這種最簡單的基本用法熟練掌握。

          源碼

          • https://github.com/gyoomi/framework

          1. IDEA這樣配置注釋模板,讓你高出一個逼格!!

          2. Java后端線上問題排查常用命令收藏

          3. OAuth2實現(xiàn)單點登錄SSO完整教程,其實不難!

          4. Redis 高負載排查記錄

          最近面試BAT,整理一份面試資料Java面試BATJ通關(guān)手冊,覆蓋了Java核心技術(shù)、JVM、Java并發(fā)、SSM、微服務、數(shù)據(jù)庫、數(shù)據(jù)結(jié)構(gòu)等等。

          獲取方式:點“在看”,關(guān)注公眾號并回復 Java 領(lǐng)取,更多內(nèi)容陸續(xù)奉上。

          文章有幫助的話,在看,轉(zhuǎn)發(fā)吧。

          謝謝支持喲 (*^__^*)

          瀏覽 59
          點贊
          評論
          收藏
          分享

          手機掃一掃分享

          分享
          舉報
          評論
          圖片
          表情
          推薦
          點贊
          評論
          收藏
          分享

          手機掃一掃分享

          分享
          舉報
          <kbd id="afajh"><form id="afajh"></form></kbd>
          <strong id="afajh"><dl id="afajh"></dl></strong>
            <del id="afajh"><form id="afajh"></form></del>
                1. <th id="afajh"><progress id="afajh"></progress></th>
                  <b id="afajh"><abbr id="afajh"></abbr></b>
                  <th id="afajh"><progress id="afajh"></progress></th>
                  日韩啪啪网站 | 天天爱天天干天天色 | 自拍偷拍第1页 | 日韩欧美国产A片 | 又大又粗免费视频 |