1.pom添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-quartz</artifactId>
</dependency>
2.配置文件添加配置
spring:
quartz:
# 使用数据库存储
job-store-type: jdbc
# 初始化完成后自动启动调度程序
autoStartup: true
properties:
org:
quartz:
# 调度器配置
scheduler:
instanceName: bootQuartzScheduler
instanceId: AUTO
# 存储配置
jobStore:
class: org.springframework.scheduling.quartz.LocalDataSourceJobStore
driverDelegateClass: org.quartz.impl.jdbcjobstore.StdJDBCDelegate
tablePrefix: qrtz_
isClustered: false
misfireThreshold: 12000
clusterCheckinInterval: 15000
useProperties: false
# 线程池配置
threadPool:
threadNamePrefix: Boot_Job_Pool
threadPriority: 5
threadCount: 10
class: org.quartz.simpl.SimpleThreadPool
3.在mysql8中执行sql生成quartz所需要的表
/*
Navicat Premium Data Transfer
Target Server Type : MySQL
Target Server Version : 80026 (8.0.26)
File Encoding : 65001
Date: 26/08/2024 18:36:19
*/
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for qrtz_blob_triggers
-- ----------------------------
DROP TABLE IF EXISTS `qrtz_blob_triggers`;
CREATE TABLE `qrtz_blob_triggers` (
`SCHED_NAME` varchar(120) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
`TRIGGER_NAME` varchar(190) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
`TRIGGER_GROUP` varchar(190) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
`BLOB_DATA` blob NULL,
PRIMARY KEY (`SCHED_NAME`, `TRIGGER_NAME`, `TRIGGER_GROUP`) USING BTREE,
INDEX `SCHED_NAME`(`SCHED_NAME` ASC, `TRIGGER_NAME` ASC, `TRIGGER_GROUP` ASC) USING BTREE,
CONSTRAINT `qrtz_blob_triggers_ibfk_1` FOREIGN KEY (`SCHED_NAME`, `TRIGGER_NAME`, `TRIGGER_GROUP`) REFERENCES `qrtz_triggers` (`SCHED_NAME`, `TRIGGER_NAME`, `TRIGGER_GROUP`) ON DELETE RESTRICT ON UPDATE RESTRICT
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Table structure for qrtz_calendars
-- ----------------------------
DROP TABLE IF EXISTS `qrtz_calendars`;
CREATE TABLE `qrtz_calendars` (
`SCHED_NAME` varchar(120) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
`CALENDAR_NAME` varchar(190) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
`CALENDAR` blob NOT NULL,
PRIMARY KEY (`SCHED_NAME`, `CALENDAR_NAME`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Table structure for qrtz_cron_triggers
-- ----------------------------
DROP TABLE IF EXISTS `qrtz_cron_triggers`;
CREATE TABLE `qrtz_cron_triggers` (
`SCHED_NAME` varchar(120) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
`TRIGGER_NAME` varchar(190) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
`TRIGGER_GROUP` varchar(190) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
`CRON_EXPRESSION` varchar(120) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
`TIME_ZONE_ID` varchar(80) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
PRIMARY KEY (`SCHED_NAME`, `TRIGGER_NAME`, `TRIGGER_GROUP`) USING BTREE,
CONSTRAINT `qrtz_cron_triggers_ibfk_1` FOREIGN KEY (`SCHED_NAME`, `TRIGGER_NAME`, `TRIGGER_GROUP`) REFERENCES `qrtz_triggers` (`SCHED_NAME`, `TRIGGER_NAME`, `TRIGGER_GROUP`) ON DELETE RESTRICT ON UPDATE RESTRICT
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Table structure for qrtz_fired_triggers
-- ----------------------------
DROP TABLE IF EXISTS `qrtz_fired_triggers`;
CREATE TABLE `qrtz_fired_triggers` (
`SCHED_NAME` varchar(120) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
`ENTRY_ID` varchar(95) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
`TRIGGER_NAME` varchar(190) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
`TRIGGER_GROUP` varchar(190) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
`INSTANCE_NAME` varchar(190) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
`FIRED_TIME` bigint NOT NULL,
`SCHED_TIME` bigint NOT NULL,
`PRIORITY` int NOT NULL,
`STATE` varchar(16) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
`JOB_NAME` varchar(190) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
`JOB_GROUP` varchar(190) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
`IS_NONCONCURRENT` varchar(1) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
`REQUESTS_RECOVERY` varchar(1) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
PRIMARY KEY (`SCHED_NAME`, `ENTRY_ID`) USING BTREE,
INDEX `IDX_QRTZ_FT_TRIG_INST_NAME`(`SCHED_NAME` ASC, `INSTANCE_NAME` ASC) USING BTREE,
INDEX `IDX_QRTZ_FT_INST_JOB_REQ_RCVRY`(`SCHED_NAME` ASC, `INSTANCE_NAME` ASC, `REQUESTS_RECOVERY` ASC) USING BTREE,
INDEX `IDX_QRTZ_FT_J_G`(`SCHED_NAME` ASC, `JOB_NAME` ASC, `JOB_GROUP` ASC) USING BTREE,
INDEX `IDX_QRTZ_FT_JG`(`SCHED_NAME` ASC, `JOB_GROUP` ASC) USING BTREE,
INDEX `IDX_QRTZ_FT_T_G`(`SCHED_NAME` ASC, `TRIGGER_NAME` ASC, `TRIGGER_GROUP` ASC) USING BTREE,
INDEX `IDX_QRTZ_FT_TG`(`SCHED_NAME` ASC, `TRIGGER_GROUP` ASC) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Table structure for qrtz_job_details
-- ----------------------------
DROP TABLE IF EXISTS `qrtz_job_details`;
CREATE TABLE `qrtz_job_details` (
`SCHED_NAME` varchar(120) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
`JOB_NAME` varchar(190) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
`JOB_GROUP` varchar(190) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
`DESCRIPTION` varchar(250) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
`JOB_CLASS_NAME` varchar(250) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
`IS_DURABLE` varchar(1) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
`IS_NONCONCURRENT` varchar(1) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
`IS_UPDATE_DATA` varchar(1) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
`REQUESTS_RECOVERY` varchar(1) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
`JOB_DATA` blob NULL,
PRIMARY KEY (`SCHED_NAME`, `JOB_NAME`, `JOB_GROUP`) USING BTREE,
INDEX `IDX_QRTZ_J_REQ_RECOVERY`(`SCHED_NAME` ASC, `REQUESTS_RECOVERY` ASC) USING BTREE,
INDEX `IDX_QRTZ_J_GRP`(`SCHED_NAME` ASC, `JOB_GROUP` ASC) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Table structure for qrtz_locks
-- ----------------------------
DROP TABLE IF EXISTS `qrtz_locks`;
CREATE TABLE `qrtz_locks` (
`SCHED_NAME` varchar(120) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
`LOCK_NAME` varchar(40) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
PRIMARY KEY (`SCHED_NAME`, `LOCK_NAME`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Table structure for qrtz_paused_trigger_grps
-- ----------------------------
DROP TABLE IF EXISTS `qrtz_paused_trigger_grps`;
CREATE TABLE `qrtz_paused_trigger_grps` (
`SCHED_NAME` varchar(120) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
`TRIGGER_GROUP` varchar(190) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
PRIMARY KEY (`SCHED_NAME`, `TRIGGER_GROUP`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Table structure for qrtz_scheduler_state
-- ----------------------------
DROP TABLE IF EXISTS `qrtz_scheduler_state`;
CREATE TABLE `qrtz_scheduler_state` (
`SCHED_NAME` varchar(120) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
`INSTANCE_NAME` varchar(190) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
`LAST_CHECKIN_TIME` bigint NOT NULL,
`CHECKIN_INTERVAL` bigint NOT NULL,
PRIMARY KEY (`SCHED_NAME`, `INSTANCE_NAME`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Table structure for qrtz_simple_triggers
-- ----------------------------
DROP TABLE IF EXISTS `qrtz_simple_triggers`;
CREATE TABLE `qrtz_simple_triggers` (
`SCHED_NAME` varchar(120) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
`TRIGGER_NAME` varchar(190) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
`TRIGGER_GROUP` varchar(190) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
`REPEAT_COUNT` bigint NOT NULL,
`REPEAT_INTERVAL` bigint NOT NULL,
`TIMES_TRIGGERED` bigint NOT NULL,
PRIMARY KEY (`SCHED_NAME`, `TRIGGER_NAME`, `TRIGGER_GROUP`) USING BTREE,
CONSTRAINT `qrtz_simple_triggers_ibfk_1` FOREIGN KEY (`SCHED_NAME`, `TRIGGER_NAME`, `TRIGGER_GROUP`) REFERENCES `qrtz_triggers` (`SCHED_NAME`, `TRIGGER_NAME`, `TRIGGER_GROUP`) ON DELETE RESTRICT ON UPDATE RESTRICT
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Table structure for qrtz_simprop_triggers
-- ----------------------------
DROP TABLE IF EXISTS `qrtz_simprop_triggers`;
CREATE TABLE `qrtz_simprop_triggers` (
`SCHED_NAME` varchar(120) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
`TRIGGER_NAME` varchar(190) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
`TRIGGER_GROUP` varchar(190) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
`STR_PROP_1` varchar(512) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
`STR_PROP_2` varchar(512) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
`STR_PROP_3` varchar(512) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
`INT_PROP_1` int NULL DEFAULT NULL,
`INT_PROP_2` int NULL DEFAULT NULL,
`LONG_PROP_1` bigint NULL DEFAULT NULL,
`LONG_PROP_2` bigint NULL DEFAULT NULL,
`DEC_PROP_1` decimal(13, 4) NULL DEFAULT NULL,
`DEC_PROP_2` decimal(13, 4) NULL DEFAULT NULL,
`BOOL_PROP_1` varchar(1) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
`BOOL_PROP_2` varchar(1) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
PRIMARY KEY (`SCHED_NAME`, `TRIGGER_NAME`, `TRIGGER_GROUP`) USING BTREE,
CONSTRAINT `qrtz_simprop_triggers_ibfk_1` FOREIGN KEY (`SCHED_NAME`, `TRIGGER_NAME`, `TRIGGER_GROUP`) REFERENCES `qrtz_triggers` (`SCHED_NAME`, `TRIGGER_NAME`, `TRIGGER_GROUP`) ON DELETE RESTRICT ON UPDATE RESTRICT
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Table structure for qrtz_triggers
-- ----------------------------
DROP TABLE IF EXISTS `qrtz_triggers`;
CREATE TABLE `qrtz_triggers` (
`SCHED_NAME` varchar(120) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
`TRIGGER_NAME` varchar(190) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
`TRIGGER_GROUP` varchar(190) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
`JOB_NAME` varchar(190) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
`JOB_GROUP` varchar(190) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
`DESCRIPTION` varchar(250) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
`NEXT_FIRE_TIME` bigint NULL DEFAULT NULL,
`PREV_FIRE_TIME` bigint NULL DEFAULT NULL,
`PRIORITY` int NULL DEFAULT NULL,
`TRIGGER_STATE` varchar(16) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
`TRIGGER_TYPE` varchar(8) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
`START_TIME` bigint NOT NULL,
`END_TIME` bigint NULL DEFAULT NULL,
`CALENDAR_NAME` varchar(190) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
`MISFIRE_INSTR` smallint NULL DEFAULT NULL,
`JOB_DATA` blob NULL,
PRIMARY KEY (`SCHED_NAME`, `TRIGGER_NAME`, `TRIGGER_GROUP`) USING BTREE,
INDEX `IDX_QRTZ_T_J`(`SCHED_NAME` ASC, `JOB_NAME` ASC, `JOB_GROUP` ASC) USING BTREE,
INDEX `IDX_QRTZ_T_JG`(`SCHED_NAME` ASC, `JOB_GROUP` ASC) USING BTREE,
INDEX `IDX_QRTZ_T_C`(`SCHED_NAME` ASC, `CALENDAR_NAME` ASC) USING BTREE,
INDEX `IDX_QRTZ_T_G`(`SCHED_NAME` ASC, `TRIGGER_GROUP` ASC) USING BTREE,
INDEX `IDX_QRTZ_T_STATE`(`SCHED_NAME` ASC, `TRIGGER_STATE` ASC) USING BTREE,
INDEX `IDX_QRTZ_T_N_STATE`(`SCHED_NAME` ASC, `TRIGGER_NAME` ASC, `TRIGGER_GROUP` ASC, `TRIGGER_STATE` ASC) USING BTREE,
INDEX `IDX_QRTZ_T_N_G_STATE`(`SCHED_NAME` ASC, `TRIGGER_GROUP` ASC, `TRIGGER_STATE` ASC) USING BTREE,
INDEX `IDX_QRTZ_T_NEXT_FIRE_TIME`(`SCHED_NAME` ASC, `NEXT_FIRE_TIME` ASC) USING BTREE,
INDEX `IDX_QRTZ_T_NFT_ST`(`SCHED_NAME` ASC, `TRIGGER_STATE` ASC, `NEXT_FIRE_TIME` ASC) USING BTREE,
INDEX `IDX_QRTZ_T_NFT_MISFIRE`(`SCHED_NAME` ASC, `MISFIRE_INSTR` ASC, `NEXT_FIRE_TIME` ASC) USING BTREE,
INDEX `IDX_QRTZ_T_NFT_ST_MISFIRE`(`SCHED_NAME` ASC, `MISFIRE_INSTR` ASC, `NEXT_FIRE_TIME` ASC, `TRIGGER_STATE` ASC) USING BTREE,
INDEX `IDX_QRTZ_T_NFT_ST_MISFIRE_GRP`(`SCHED_NAME` ASC, `MISFIRE_INSTR` ASC, `NEXT_FIRE_TIME` ASC, `TRIGGER_GROUP` ASC, `TRIGGER_STATE` ASC) USING BTREE,
CONSTRAINT `qrtz_triggers_ibfk_1` FOREIGN KEY (`SCHED_NAME`, `JOB_NAME`, `JOB_GROUP`) REFERENCES `qrtz_job_details` (`SCHED_NAME`, `JOB_NAME`, `JOB_GROUP`) ON DELETE RESTRICT ON UPDATE RESTRICT
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Table structure for quartz_job
-- ----------------------------
DROP TABLE IF EXISTS `quartz_job`;
CREATE TABLE `quartz_job` (
`id` int NOT NULL AUTO_INCREMENT COMMENT '任务id',
`bean_name` varchar(200) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT 'SpringBean名称',
`params` varchar(2000) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '执行参数',
`cron_expres` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT 'cron表达式',
`state` int NULL DEFAULT NULL COMMENT '任务状态:1正常,2暂停,3删除',
`remark` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '备注',
`create_time` datetime NULL DEFAULT NULL COMMENT '创建时间',
`update_time` datetime NULL DEFAULT NULL COMMENT '更新时间',
`is_deleted` varchar(2) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT '0' COMMENT '是否删除:0否,1是',
`rule_id` int NULL DEFAULT NULL COMMENT '规则ID',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 33 CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = '任务列表' ROW_FORMAT = Dynamic;
-- ----------------------------
-- Table structure for quartz_log
-- ----------------------------
DROP TABLE IF EXISTS `quartz_log`;
CREATE TABLE `quartz_log` (
`id` bigint NOT NULL AUTO_INCREMENT COMMENT '任务日志id',
`job_id` int NOT NULL COMMENT '任务id',
`bean_name` varchar(200) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT 'SpringBean名称',
`params` varchar(2000) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '执行参数',
`state` tinyint NOT NULL COMMENT '任务状态:1成功,2失败',
`error` varchar(2000) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '失败信息',
`times` int NOT NULL COMMENT '耗时(单位:毫秒)',
`create_time` datetime NULL DEFAULT NULL COMMENT '创建时间',
PRIMARY KEY (`id`) USING BTREE,
INDEX `job_id`(`job_id` ASC) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 99 CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = '任务日志' ROW_FORMAT = Dynamic;
SET FOREIGN_KEY_CHECKS = 1;
4.在mysql8中执行sql生成记录定时任务和执行的表
/*
Navicat Premium Data Transfer
Target Server Type : MySQL
Target Server Version : 80026 (8.0.26)
File Encoding : 65001
Date: 26/08/2024 18:39:55
*/
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for quartz_job
-- ----------------------------
DROP TABLE IF EXISTS `quartz_job`;
CREATE TABLE `quartz_job` (
`id` int NOT NULL AUTO_INCREMENT COMMENT '任务id',
`bean_name` varchar(200) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT 'SpringBean名称',
`params` varchar(2000) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '执行参数',
`cron_expres` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT 'cron表达式',
`state` int NULL DEFAULT NULL COMMENT '任务状态:1正常,2暂停,3删除',
`remark` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '备注',
`create_time` datetime NULL DEFAULT NULL COMMENT '创建时间',
`update_time` datetime NULL DEFAULT NULL COMMENT '更新时间',
`is_deleted` varchar(2) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT '0' COMMENT '是否删除:0否,1是',
`rule_id` int NULL DEFAULT NULL COMMENT '规则ID',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 33 CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = '任务列表' ROW_FORMAT = Dynamic;
-- ----------------------------
-- Table structure for quartz_log
-- ----------------------------
DROP TABLE IF EXISTS `quartz_log`;
CREATE TABLE `quartz_log` (
`id` bigint NOT NULL AUTO_INCREMENT COMMENT '任务日志id',
`job_id` int NOT NULL COMMENT '任务id',
`bean_name` varchar(200) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT 'SpringBean名称',
`params` varchar(2000) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '执行参数',
`state` tinyint NOT NULL COMMENT '任务状态:1成功,2失败',
`error` varchar(2000) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '失败信息',
`times` int NOT NULL COMMENT '耗时(单位:毫秒)',
`create_time` datetime NULL DEFAULT NULL COMMENT '创建时间',
PRIMARY KEY (`id`) USING BTREE,
INDEX `job_id`(`job_id` ASC) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 99 CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = '任务日志' ROW_FORMAT = Dynamic;
SET FOREIGN_KEY_CHECKS = 1;
5.生成quartz_job和quartz_log两张表的实体类、mapper.xml和mapper.java。
quartz_job:保存需要执行的定时任务;
quartz_log:保存定时任务执行的结果;
6.定时任务配置类
import com.domain.QuartzJob;
import com.enums.JobState;
import org.quartz.*;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
/**
* 任务操作基础封装
* @author
* @since 2023-07-26 14:04
*/
@Component
public class QuartzManage {
private static final String SCHEDULE_NAME = "BOOT_JOB_" ;
@Resource
private Scheduler scheduler ;
/**
* 触发器 KEY
*/
public TriggerKey getTriggerKey(Integer jobId){
return TriggerKey.triggerKey(SCHEDULE_NAME+jobId) ;
}
/**
* 定时任务 Key
*/
public JobKey getJobKey (Integer jobId){
return JobKey.jobKey(SCHEDULE_NAME+jobId) ;
}
/**
* 表达式触发器
*/
public CronTrigger getCronTrigger (Integer jobId){
try {
return (CronTrigger) this.scheduler.getTrigger(getTriggerKey(jobId)) ;
} catch (SchedulerException e){
throw new RuntimeException("getCronTrigger Fail",e) ;
}
}
/**
* 创建定时器
*/
public void createJob (QuartzJob quartzJob){
try {
// 构建任务
JobDetail jobDetail = JobBuilder.newJob(QuartzRecord.class)
.withIdentity(getJobKey(quartzJob.getId())).build() ;
// 构建Cron调度器
CronScheduleBuilder scheduleBuilder = CronScheduleBuilder
.cronSchedule(quartzJob.getCronExpres())
.withMisfireHandlingInstructionDoNothing() ;
// 任务触发器
CronTrigger trigger = TriggerBuilder.newTrigger()
.withIdentity(getTriggerKey(quartzJob.getId()))
.withSchedule(scheduleBuilder).build() ;
jobDetail.getJobDataMap().put(QuartzJob.JOB_PARAM_KEY,quartzJob);
scheduler.scheduleJob(jobDetail,trigger) ;
// 状态校验
checkStop(quartzJob) ;
} catch (SchedulerException e){
e.printStackTrace();
throw new RuntimeException("createJob Fail",e) ;
}
}
/**
* 更新定时任务
*/
public void updateJob(QuartzJob quartzJob) {
try {
// 查询触发器Key
TriggerKey triggerKey = getTriggerKey(quartzJob.getId());
// 构建Cron调度器
CronScheduleBuilder scheduleBuilder = CronScheduleBuilder
.cronSchedule(quartzJob.getCronExpres())
.withMisfireHandlingInstructionDoNothing();
// 任务触发器
CronTrigger trigger = getCronTrigger(quartzJob.getId())
.getTriggerBuilder()
.withIdentity(triggerKey)
.withSchedule(scheduleBuilder).build();
trigger.getJobDataMap().put(QuartzJob.JOB_PARAM_KEY, quartzJob);
scheduler.rescheduleJob(triggerKey, trigger);
// 状态校验
checkStop(quartzJob) ;
} catch (SchedulerException e) {
e.printStackTrace();
throw new RuntimeException("updateJob Fail",e) ;
}
}
/**
* 恢复定时器
*/
public void resumeJob (Integer jobId){
try {
this.scheduler.resumeJob(getJobKey(jobId));
} catch (SchedulerException e){
e.printStackTrace();
throw new RuntimeException("resumeJob Fail",e) ;
}
}
/**
* 删除定时器
*/
public void deleteJob (Integer jobId){
try {
scheduler.deleteJob(getJobKey(jobId));
} catch (SchedulerException e){
e.printStackTrace();
throw new RuntimeException("deleteJob Fail",e) ;
}
}
/**
* 执行定时器
*/
public void run (QuartzJob quartzJob){
try {
JobDataMap dataMap = new JobDataMap() ;
dataMap.put(QuartzJob.JOB_PARAM_KEY,quartzJob);
this.scheduler.triggerJob(getJobKey(quartzJob.getId()),dataMap);
} catch (SchedulerException e){
e.printStackTrace();
throw new RuntimeException("run Fail",e) ;
}
}
/**
* 校验停止定时器
*/
public void checkStop (QuartzJob quartzJob){
try {
if(quartzJob.getState() != JobState.JOB_RUN.getStatus()){
this.scheduler.pauseJob(getJobKey(quartzJob.getId()));
}else {
if(!this.scheduler.isShutdown()){
this.scheduler.start();
}
}
} catch (SchedulerException e){
e.printStackTrace();
throw new RuntimeException("pauseJob Fail",e) ;
}
}
}
7.定时任务执行状态枚举类
package com.enums;
public enum JobState {
JOB_RUN(1, "运行"),
JOB_STOP(2, "暂停"),
JOB_DEL(3, "删除");
private int status;
private String desc;
JobState(int status, String desc) {
this.status = status;
this.desc = desc;
}
public int getStatus() {
return status;
}
public String getDesc() {
return desc;
}
}
8.定时任务日志枚举类
package com.enums;
public enum LogState {
LOG_SUS(1, "成功"),
LOG_FAIL(2, "失败");
private int status;
private String desc;
LogState(int status, String desc) {
this.status = status;
this.desc = desc;
}
public int getStatus() {
return status;
}
public String getDesc() {
return desc;
}
}
9.定时任务执行类1
package com.quartz;
import cn.hutool.json.JSONObject;
import com.domain.QuartzJob;
import com.domain.QuartzLog;
import com.domain.SysCollectionRule;
import com.enums.ConstantsEnum;
import com.enums.LogState;
import com.service.QuartzLogService;
import com.service.impl.SysCollectionRuleServiceImpl;
import com.utils.SpringUtil;
import com.utils.TransferObjectUtil;
import org.apache.commons.lang3.StringUtils;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.JobExecutionContext;
import org.quartz.PersistJobDataAfterExecution;
import org.springframework.scheduling.quartz.QuartzJobBean;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
@PersistJobDataAfterExecution
@DisallowConcurrentExecution
public class QuartzRecord extends QuartzJobBean {
@Override
protected void executeInternal(JobExecutionContext context) {
// QuartzJob quartzJob = (QuartzJob)context.getMergedJobDataMap().get(QuartzJob.JOB_PARAM_KEY) ;
Object o = context.getMergedJobDataMap().get(QuartzJob.JOB_PARAM_KEY);
JSONObject quartzJob = new JSONObject(o);
// QuartzLogService quartzLogService = (QuartzLogService) SpringUtil.getBean("quartzLogService") ;
// QuartzManage quartzManage = (QuartzManage) SpringUtil.getBean("quartzManage") ;
// 定时器日志记录
// QuartzLog quartzLog = new QuartzLog () ;
// quartzLog.setJobId(quartzJob.getInt("id"));
// quartzLog.setBeanName(quartzJob.getStr("beanName"));
// quartzLog.setParams(quartzJob.getStr("params"));
// quartzLog.setCreateTime(new Date());
// long beginTime = System.currentTimeMillis() ;
// String error = "";
try {
// 加载并执行
Object target = SpringUtil.getBean(quartzJob.getStr("beanName"));
if(StringUtils.isNotEmpty(quartzJob.getStr("params"))){
Method method = target.getClass().getDeclaredMethod("run", String.class);
method.invoke(target, quartzJob.getStr("params"));
}else {
Method method = target.getClass().getDeclaredMethod("run");
method.invoke(target);
}
// Integer id = Integer.parseInt(quartzJob.getStr("params"));
// SysCollectionRule rule = ruleService.getOneById(id);
//
// if(Objects.nonNull(rule)){
// List<Map<String, Object>> maps = transferObjectUtil.transferObj(rule);
//
// if(null!=maps&&!maps.isEmpty()){
// quartzLog.setState(LogState.LOG_SUS.getStatus());
// }else {
// quartzLog.setState(LogState.LOG_FAIL.getStatus());
// quartzLog.setError("新增或更新数据失败");
// }
// }else {
// quartzLog.setError("规则对象不存在");
// quartzLog.setState(LogState.LOG_FAIL.getStatus());
// }
//
//
// if(rule.getDataCollectionTime().contains("\"jobType\":0")){//如果是只执行一次的定时任务,任务完成后删除
// quartzManage.deleteJob(quartzJob.getInt("id"));
// //修改定时任务为删除,这样项目重启的时候不会把该任务加入定时器中
// ruleService.updateJobStatusById(quartzJob.getInt("id"));
// }
// quartzLog.setState(LogState.LOG_SUS.getStatus());
// long executeTime = System.currentTimeMillis() - beginTime;
// quartzLog.setTimes((int)executeTime);
} catch (Exception e){
// 异常信息
// error=e.getMessage();
// long executeTime = System.currentTimeMillis() - beginTime;
// quartzLog.setTimes((int)executeTime);
// quartzLog.setState(LogState.LOG_FAIL.getStatus());
// quartzLog.setError(error);
e.printStackTrace();
} finally {
// 保存执行日志
// quartzLogService.insert(quartzLog) ;
}
}
}
10.定时任务执行类2
import com.QuartzJob;
import com.QuartzLog;
import com.LogState;
import com.QuartzLogService;
import com.SpringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import java.time.LocalDateTime;
import java.util.*;
@Slf4j
@Component
public class MyJob {
public void run(String params) throws Exception {
QuartzManage quartzManage = (QuartzManage) SpringUtil.getBean("quartzManage") ;
QuartzLogService quartzLogService = (QuartzLogService) SpringUtil.getBean("quartzLogService") ;
log.info("----------------------------MyJob.start------------------------"+ LocalDateTime.now());
Integer id = Integer.parseInt(params);
QuartzJob quartzJob = new QuartzJob();
// 定时器日志记录
QuartzLog quartzLog = new QuartzLog () ;
quartzLog.setJobId(quartzJob.getId());
quartzLog.setBeanName(quartzJob.getBeanName());
quartzLog.setParams(quartzJob.getParams());
quartzLog.setCreateTime(new Date());
long beginTime = System.currentTimeMillis() ;
String error = "";
try {
//需要执行定时任务的业务逻辑
long executeTime = System.currentTimeMillis() - beginTime;
quartzLog.setTimes((int)executeTime);
quartzLog.setState(LogState.LOG_SUS.getStatus());
}catch (Exception e){
// 异常信息
error=e.getMessage();
long executeTime = System.currentTimeMillis() - beginTime;
quartzLog.setTimes((int)executeTime);
quartzLog.setState(LogState.LOG_FAIL.getStatus());
quartzLog.setError(error);
e.printStackTrace();
}finally {
// 保存执行日志
quartzLogService.insert(quartzLog) ;
}
log.info("----------------------------MyJob.end------------------------"+LocalDateTime.now());
}
}
注意,实现定时任务时第9步和第10步都需要,第10步是具体需要执行的业务逻辑,第9步是quartz执行定时任务的逻辑。
11.操作定时任务
新增定时任务
//新增定时任务
QuartzJob quartzJob = QuartzJob.builder().cronExpres(cron).beanName("myJob").state(JOB_RUN.getStatus()).
ruleId(id).params(String.valueOf(id)).createTime(new Date()).build();
int flag = quartzJobMapper.insert(quartzJob);
if (flag > 0){
quartzManage.createJob(quartzJob) ;
}
更新定时任务,更新时需要先删除再新增
//删除定时任务
QuartzJob quartzJob = quartzJobMapper.selectOne(new QueryWrapper<QuartzJob>().eq("id", id));
if(Objects.nonNull(quartzJob)){
quartzManage.deleteJob(quartzJob.getId());
}
//新增定时任务
quartzJob.setBeanName("myJob");
quartzJob.setCronExpres(cron);
quartzJob.setState(JOB_RUN.getStatus());
quartzJob.setParams(String.valueOf(id));
quartzJob.setUpdateTime(new Date());
int flag = quartzJobMapper.updateById(quartzJob);
if (flag > 0){
//先删除,后新增
quartzManage.createJob(quartzJob);
}
注意,如果定时任务是只执行一次,配置cron表达式时指定到时分秒,此时定时任务会立即执行,如果定时任务是重复执行,比如每隔一小时执行一次,此时定时任务不会立即执行。