• Spring Boot集成Quartz快速入门Demo


    1.Quartz介绍

      Quartz是OpenSymphony开源的一个项目,是一个由Java编写的开源作业调度框架。

    特点

    1. 支持分布式高可用,我们需要某个定时任务在多个节点中只有某个节点可以执行时,就需要Quartz来实现,否则使用@Scheduled等方式会造成所有节点都执行一遍。

    2. 支持持久化,Quartz有专门的数据表来实现定时任务的持久化。

    3. 支持多任务调度和管理,Quartz可以在数据库中存储多个定时任务进行作业调度,可以实现定时任务的增删改查等管理。

    组成

    Quartz由三部分组成:

    1. 任务:JobDetail

    2. 触发器:Trigger(分为SimpleTrigger和CronTrigger)

    3. 调度器:Scheduler

    2.mysql环境搭建

    第一个mysql数据库

    docker run --name docker-mysql -e MYSQL_ROOT_PASSWORD=123456 -p 3306:3306 -d mysql

    初始化数据

    1. create database demo;
    2. #
    3. # Quartz seems to work best with the driver mm.mysql-2.0.7-bin.jar
    4. #
    5. # PLEASE consider using mysql with innodb tables to avoid locking issues
    6. #
    7. # In your Quartz properties file, you'll need to set
    8. # org.quartz.jobStore.driverDelegateClass = org.quartz.impl.jdbcjobstore.StdJDBCDelegate
    9. #
    10. DROP TABLE IF EXISTS QRTZ_FIRED_TRIGGERS;
    11. DROP TABLE IF EXISTS QRTZ_PAUSED_TRIGGER_GRPS;
    12. DROP TABLE IF EXISTS QRTZ_SCHEDULER_STATE;
    13. DROP TABLE IF EXISTS QRTZ_LOCKS;
    14. DROP TABLE IF EXISTS QRTZ_SIMPLE_TRIGGERS;
    15. DROP TABLE IF EXISTS QRTZ_SIMPROP_TRIGGERS;
    16. DROP TABLE IF EXISTS QRTZ_CRON_TRIGGERS;
    17. DROP TABLE IF EXISTS QRTZ_BLOB_TRIGGERS;
    18. DROP TABLE IF EXISTS QRTZ_TRIGGERS;
    19. DROP TABLE IF EXISTS QRTZ_JOB_DETAILS;
    20. DROP TABLE IF EXISTS QRTZ_CALENDARS;CREATE TABLE QRTZ_JOB_DETAILS
    21. (
    22. SCHED_NAME VARCHAR(120) NOT NULL,
    23. JOB_NAME VARCHAR(200) NOT NULL,
    24. JOB_GROUP VARCHAR(200) NOT NULL,
    25. DESCRIPTION VARCHAR(250) NULL,
    26. JOB_CLASS_NAME VARCHAR(250) NOT NULL,
    27. IS_DURABLE VARCHAR(1) NOT NULL,
    28. IS_NONCONCURRENT VARCHAR(1) NOT NULL,
    29. IS_UPDATE_DATA VARCHAR(1) NOT NULL,
    30. REQUESTS_RECOVERY VARCHAR(1) NOT NULL,
    31. JOB_DATA BLOB NULL,
    32. PRIMARY KEY (SCHED_NAME,JOB_NAME,JOB_GROUP)
    33. );
    34. CREATE TABLE QRTZ_TRIGGERS
    35. (
    36. SCHED_NAME VARCHAR(120) NOT NULL,
    37. TRIGGER_NAME VARCHAR(200) NOT NULL,
    38. TRIGGER_GROUP VARCHAR(200) NOT NULL,
    39. JOB_NAME VARCHAR(200) NOT NULL,
    40. JOB_GROUP VARCHAR(200) NOT NULL,
    41. DESCRIPTION VARCHAR(250) NULL,
    42. NEXT_FIRE_TIME BIGINT(13) NULL,
    43. PREV_FIRE_TIME BIGINT(13) NULL,
    44. PRIORITY INTEGER NULL,
    45. TRIGGER_STATE VARCHAR(16) NOT NULL,
    46. TRIGGER_TYPE VARCHAR(8) NOT NULL,
    47. START_TIME BIGINT(13) NOT NULL,
    48. END_TIME BIGINT(13) NULL,
    49. CALENDAR_NAME VARCHAR(200) NULL,
    50. MISFIRE_INSTR SMALLINT(2) NULL,
    51. JOB_DATA BLOB NULL,
    52. PRIMARY KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP),
    53. FOREIGN KEY (SCHED_NAME,JOB_NAME,JOB_GROUP)
    54. REFERENCES QRTZ_JOB_DETAILS(SCHED_NAME,JOB_NAME,JOB_GROUP)
    55. );
    56. CREATE TABLE QRTZ_SIMPLE_TRIGGERS
    57. (
    58. SCHED_NAME VARCHAR(120) NOT NULL,
    59. TRIGGER_NAME VARCHAR(200) NOT NULL,
    60. TRIGGER_GROUP VARCHAR(200) NOT NULL,
    61. REPEAT_COUNT BIGINT(7) NOT NULL,
    62. REPEAT_INTERVAL BIGINT(12) NOT NULL,
    63. TIMES_TRIGGERED BIGINT(10) NOT NULL,
    64. PRIMARY KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP),
    65. FOREIGN KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP)
    66. REFERENCES QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP)
    67. );
    68. CREATE TABLE QRTZ_CRON_TRIGGERS
    69. (
    70. SCHED_NAME VARCHAR(120) NOT NULL,
    71. TRIGGER_NAME VARCHAR(200) NOT NULL,
    72. TRIGGER_GROUP VARCHAR(200) NOT NULL,
    73. CRON_EXPRESSION VARCHAR(200) NOT NULL,
    74. TIME_ZONE_ID VARCHAR(80),
    75. PRIMARY KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP),
    76. FOREIGN KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP)
    77. REFERENCES QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP)
    78. );
    79. CREATE TABLE QRTZ_SIMPROP_TRIGGERS
    80. (
    81. SCHED_NAME VARCHAR(120) NOT NULL,
    82. TRIGGER_NAME VARCHAR(200) NOT NULL,
    83. TRIGGER_GROUP VARCHAR(200) NOT NULL,
    84. STR_PROP_1 VARCHAR(512) NULL,
    85. STR_PROP_2 VARCHAR(512) NULL,
    86. STR_PROP_3 VARCHAR(512) NULL,
    87. INT_PROP_1 INT NULL,
    88. INT_PROP_2 INT NULL,
    89. LONG_PROP_1 BIGINT NULL,
    90. LONG_PROP_2 BIGINT NULL,
    91. DEC_PROP_1 NUMERIC(13,4) NULL,
    92. DEC_PROP_2 NUMERIC(13,4) NULL,
    93. BOOL_PROP_1 VARCHAR(1) NULL,
    94. BOOL_PROP_2 VARCHAR(1) NULL,
    95. PRIMARY KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP),
    96. FOREIGN KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP)
    97. REFERENCES QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP)
    98. );
    99. CREATE TABLE QRTZ_BLOB_TRIGGERS
    100. (
    101. SCHED_NAME VARCHAR(120) NOT NULL,
    102. TRIGGER_NAME VARCHAR(200) NOT NULL,
    103. TRIGGER_GROUP VARCHAR(200) NOT NULL,
    104. BLOB_DATA BLOB NULL,
    105. PRIMARY KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP),
    106. FOREIGN KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP)
    107. REFERENCES QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP)
    108. );
    109. CREATE TABLE QRTZ_CALENDARS
    110. (
    111. SCHED_NAME VARCHAR(120) NOT NULL,
    112. CALENDAR_NAME VARCHAR(200) NOT NULL,
    113. CALENDAR BLOB NOT NULL,
    114. PRIMARY KEY (SCHED_NAME,CALENDAR_NAME)
    115. );
    116. CREATE TABLE QRTZ_PAUSED_TRIGGER_GRPS
    117. (
    118. SCHED_NAME VARCHAR(120) NOT NULL,
    119. TRIGGER_GROUP VARCHAR(200) NOT NULL,
    120. PRIMARY KEY (SCHED_NAME,TRIGGER_GROUP)
    121. );
    122. CREATE TABLE QRTZ_FIRED_TRIGGERS
    123. (
    124. SCHED_NAME VARCHAR(120) NOT NULL,
    125. ENTRY_ID VARCHAR(95) NOT NULL,
    126. TRIGGER_NAME VARCHAR(200) NOT NULL,
    127. TRIGGER_GROUP VARCHAR(200) NOT NULL,
    128. INSTANCE_NAME VARCHAR(200) NOT NULL,
    129. FIRED_TIME BIGINT(13) NOT NULL,
    130. SCHED_TIME BIGINT(13) NOT NULL,
    131. PRIORITY INTEGER NOT NULL,
    132. STATE VARCHAR(16) NOT NULL,
    133. JOB_NAME VARCHAR(200) NULL,
    134. JOB_GROUP VARCHAR(200) NULL,
    135. IS_NONCONCURRENT VARCHAR(1) NULL,
    136. REQUESTS_RECOVERY VARCHAR(1) NULL,
    137. PRIMARY KEY (SCHED_NAME,ENTRY_ID)
    138. );
    139. CREATE TABLE QRTZ_SCHEDULER_STATE
    140. (
    141. SCHED_NAME VARCHAR(120) NOT NULL,
    142. INSTANCE_NAME VARCHAR(200) NOT NULL,
    143. LAST_CHECKIN_TIME BIGINT(13) NOT NULL,
    144. CHECKIN_INTERVAL BIGINT(13) NOT NULL,
    145. PRIMARY KEY (SCHED_NAME,INSTANCE_NAME)
    146. );
    147. CREATE TABLE QRTZ_LOCKS
    148. (
    149. SCHED_NAME VARCHAR(120) NOT NULL,
    150. LOCK_NAME VARCHAR(40) NOT NULL,
    151. PRIMARY KEY (SCHED_NAME,LOCK_NAME)
    152. );
    153. commit;

    说明

    1. msyql账号root
    2. mysql密码123456

    3.代码工程

    实验目的:创建一个cron的quartz定时任务,并持久化到数据库

    pom.xml

    1. "1.0" encoding="UTF-8"?>
    2. <project xmlns="http://maven.apache.org/POM/4.0.0"
    3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    5. <parent>
    6. <artifactId>springboot-demoartifactId>
    7. <groupId>com.etgroupId>
    8. <version>1.0-SNAPSHOTversion>
    9. parent>
    10. <modelVersion>4.0.0modelVersion>
    11. <artifactId>quartzartifactId>
    12. <properties>
    13. <maven.compiler.source>8maven.compiler.source>
    14. <maven.compiler.target>8maven.compiler.target>
    15. properties>
    16. <dependencies>
    17. <dependency>
    18. <groupId>org.springframework.bootgroupId>
    19. <artifactId>spring-boot-starter-webartifactId>
    20. dependency>
    21. <dependency>
    22. <groupId>org.springframework.bootgroupId>
    23. <artifactId>spring-boot-autoconfigureartifactId>
    24. dependency>
    25. <dependency>
    26. <groupId>org.springframework.bootgroupId>
    27. <artifactId>spring-boot-starter-testartifactId>
    28. <scope>testscope>
    29. dependency>
    30. <dependency>
    31. <groupId>org.springframework.bootgroupId>
    32. <artifactId>spring-boot-starter-quartzartifactId>
    33. dependency>
    34. <dependency>
    35. <groupId>mysqlgroupId>
    36. <artifactId>mysql-connector-javaartifactId>
    37. dependency>
    38. <dependency>
    39. <groupId>org.projectlombokgroupId>
    40. <artifactId>lombokartifactId>
    41. <optional>trueoptional>
    42. dependency>
    43. <dependency>
    44. <groupId>org.springframework.bootgroupId>
    45. <artifactId>spring-boot-starter-jdbcartifactId>
    46. dependency>
    47. dependencies>
    48. project>

    Application.yaml

    1. server:
    2. port: 8088
    3. spring:
    4. datasource:
    5. quartz:
    6. driver-class-name: com.mysql.cj.jdbc.Driver
    7. url: jdbc:mysql://localhost:3306/demo?serverTimezone=GMT%2B8
    8. username: root
    9. password: 123456
    10. quartz:
    11. job-store-type: jdbc # use jdbc databse
    12. scheduler-name: hyhScheduler # 相同 Scheduler 名字的节点,形成一个 Quartz 集群
    13. wait-for-jobs-to-complete-on-shutdown: true # 应用关闭时,是否等待定时任务执行完成。默认为 false ,建议设置为 true
    14. jdbc:
    15. initialize-schema: never # 是否自动使用 SQL 初始化 Quartz 表结构。这里设置成 never ,我们手动创建表结构。
    16. properties:
    17. org:
    18. quartz:
    19. # JobStore 相关配置
    20. jobStore:
    21. dataSource: quartzDataSource # 使用的数据源
    22. class: org.quartz.impl.jdbcjobstore.JobStoreTX # JobStore 实现类
    23. driverDelegateClass: org.quartz.impl.jdbcjobstore.StdJDBCDelegate
    24. tablePrefix: QRTZ_ # Quartz 表前缀
    25. isClustered: true # 是集群模式
    26. clusterCheckinInterval: 1000
    27. useProperties: false
    28. # 线程池相关配置
    29. threadPool:
    30. threadCount: 25 # 线程池大小。默认为 10 。
    31. threadPriority: 5 # 线程优先级
    32. class: org.quartz.simpl.SimpleThreadPool # 线程池类型

    job

    打印出当前线程名、当前时间及当前调用次数

    1. package com.et.quartz.job;
    2. import org.quartz.JobExecutionContext;
    3. import org.quartz.JobExecutionException;
    4. import org.springframework.scheduling.quartz.QuartzJobBean;
    5. import java.time.LocalDateTime;
    6. import java.time.format.DateTimeFormatter;
    7. import java.util.concurrent.atomic.AtomicInteger;
    8. //SimpleJob是一个简单定时任务体,用于打印出当前线程名、当前时间及当前调用次数
    9. public class SimpleJob extends QuartzJobBean {
    10. private final static AtomicInteger counter = new AtomicInteger(1);
    11. @Override
    12. protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
    13. LocalDateTime now = LocalDateTime.now();
    14. String name = Thread.currentThread().getName();
    15. System.out.println("Execute quartz \"SimpleJob\", threadName = \"" + name +
    16. "\", the " + counter.getAndIncrement() + "th execution, time = \"" +
    17. now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS")) + "\"");
    18. }
    19. }

    Jobinit.java

    job初始化,并将相关数据持久化都数据库

    1. package com.et.quartz.config;
    2. import com.et.quartz.job.SimpleJob;
    3. import org.quartz.*;
    4. import org.springframework.beans.factory.annotation.Autowired;
    5. import org.springframework.boot.ApplicationArguments;
    6. import org.springframework.boot.ApplicationRunner;
    7. import org.springframework.stereotype.Component;
    8. import java.util.HashSet;
    9. import java.util.Set;
    10. @Component
    11. public class JobInit implements ApplicationRunner {
    12. private static final String ID = "SUMMERDAY";
    13. @Autowired
    14. private Scheduler scheduler;
    15. @Override
    16. public void run(ApplicationArguments args) throws Exception {
    17. JobDetail jobDetail = JobBuilder.newJob(SimpleJob.class)
    18. .withIdentity(ID + " 02")
    19. .storeDurably()
    20. .build();
    21. CronScheduleBuilder scheduleBuilder =
    22. CronScheduleBuilder.cronSchedule("0/10 * * * * ? *");
    23. //create task trigger
    24. Trigger trigger = TriggerBuilder.newTrigger()
    25. .forJob(jobDetail)
    26. .withIdentity(ID + " 02Trigger")
    27. .withSchedule(scheduleBuilder)
    28. .startNow() //exceute Now
    29. .build();
    30. Set<Trigger> set = new HashSet<>();
    31. set.add(trigger);
    32. // boolean replace it will replace quartz's task in database when the task is started
    33. scheduler.scheduleJob(jobDetail, set, true);
    34. }
    35. }

    DemoApplication.java

    1. package com.et.quartz;
    2. import org.springframework.boot.SpringApplication;
    3. import org.springframework.boot.autoconfigure.SpringBootApplication;
    4. @SpringBootApplication
    5. public class DemoApplication {
    6. public static void main(String[] args) {
    7. SpringApplication.run(DemoApplication.class, args);
    8. }
    9. }

    以上只是一些关键代码,所有代码请参见下面代码仓库

    代码仓库

    • https://github.com/Harries/springboot-demo

    4.测试

    启动Spring Boot应用,发现每10秒运行一次定时任务

    1. Execute quartz "SimpleJob", threadName = "hyhScheduler_Worker-1", the 1th execution, time = "2024-04-23 09:14:23.031"
    2. Execute quartz "SimpleJob", threadName = "hyhScheduler_Worker-2", the 2th execution, time = "2024-04-23 09:14:30.019"
    3. Execute quartz "SimpleJob", threadName = "hyhScheduler_Worker-3", the 3th execution, time = "2024-04-23 09:14:40.015"
    4. Execute quartz "SimpleJob", threadName = "hyhScheduler_Worker-4", the 4th execution, time = "2024-04-23 09:14:50.017"
    5. Execute quartz "SimpleJob", threadName = "hyhScheduler_Worker-5", the 5th execution, time = "2024-04-23 09:15:00.022"
    6. Execute quartz "SimpleJob", threadName = "hyhScheduler_Worker-6", the 6th execution, time = "2024-04-23 09:15:10.024"

    查看是否数据库有任务信息

    1. select * from QRTZ_SIMPLE_TRIGGERS qst
    2. select * from QRTZ_CRON_TRIGGERS qct

    8ba82361fa2727eb68f91ca4774e9308.png

    5.参考引用

    • https://www.cnblogs.com/summerday152/p/14193968.html

    • http://www.liuhaihua.cn/archives/710458.html

  • 相关阅读:
    【愚公系列】2022年10月 LiteDB数据库-.Net Core中的使用
    优维EasyOps®全平台又一波新功能上线,操作体验更带劲
    springboot集成mysql、mybatis-plus、shardingsphere-jdbc实现读写分离
    JWT 安全及案例实战
    C++——继承
    SQLMaestro PHP Generator v2022 Crack
    JZM-D30室温探针台技术参数
    ORA-00600 【3948】,ORA-00600 【3949】
    ClickHouse副本节点数据损坏恢复
    Redis学习笔记-003
  • 原文地址:https://blog.csdn.net/dot_life/article/details/138149740