Spring Boot 中使用 Quartz 基本介紹

我們在上一篇有跟大家介紹如何簡單的在 Spring Boot 中使用 Scheduler,但是當系統比較龐大或是有比較多的排程任務需求時,我們就會需要一個排程框架來輔助我們,這邊我推薦的是 Quartz

我們先來看看他的官網上是怎麼介紹他自己的吧!

Quartz is a richly featured, open source job scheduling library that can be integrated within virtually any Java application - from the smallest stand-alone application to the largest e-commerce system. Quartz can be used to create simple or complex schedules for executing tens, hundreds, or even tens-of-thousands of jobs; jobs whose tasks are defined as standard Java components that may execute virtually anything you may program them to do. The Quartz Scheduler includes many enterprise-class features, such as support for JTA transactions and clustering.

簡單的說,就是 Quartz 是一個功能豐富且開源的排程框架。可以讓我們輕易地使用在 Java 的專案中。

Quick Start

在 Spring Boot 2.0 中,已經有提供了 spring-boot-starter 的快速建置方式

  • pom.xml 添加依賴

    1
    2
    3
    4
    <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-quartz</artifactId>
    </dependency>
  • application.yml 設定

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    spring:
    quartz:
    job-store-type: jdbc
    initialize-schema: embedded
    properties:
    org:
    quartz:
    scheduler:
    instanceName: MyScheduler
    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
  • 建立資料表
    我們可以在官網下載 2.2.3 的版本中
    在資料夾 quartz-2.2.3/docs/dbTables 裡面可以根據你使用的 Database 去建立相關的表格

tables_mysql.sql

  • 建立你的 Job
    TestJob.java

    1
    2
    3
    4
    5
    6
    7
    public class TestJob extends QuartzJobBean {

    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
    System.out.println("Job exec!");
    }
    }
  • 設定 Quartz Config
    QuartzConfig.java

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    @Configuration
    public class QuartzConfig {

    @Bean
    public JobDetail testQuartz1() {
    return JobBuilder.newJob(TestJob.class).withIdentity("testTask1").storeDurably().build();
    }

    @Bean
    public Trigger testQuartzTrigger1() {
    //5秒执行一次
    SimpleScheduleBuilder scheduleBuilder = SimpleScheduleBuilder.simpleSchedule()
    .withIntervalInSeconds(5)
    .repeatForever();
    return TriggerBuilder.newTrigger().forJob(testQuartz1())
    .withIdentity("testTask1")
    .withSchedule(scheduleBuilder)
    .build();
    }
    }
  • 驗證結果

如果有其他問題,歡迎寄信討論!謝謝!

Reference

Quartz

謝謝您的支持與鼓勵

Ads