Spring Boot项目中使用Quartz完成定时任务

都说好记性不如烂笔头,每天写一点,从量变到质变的开始!废话不多说,以下所有内容均来自本人实际操作:

前言:现在项目中定时任务一般都使用Quartz框架,Java虽然提供了Timer类但是一般都不用. Spring Boot整合了Quartz框架,用起来很方便,在此记录一下基本配置和实现.

环境:Windows10+JDK8+Spring Boot+Mysql8+Mybatis-Plus+Quartz

1.Spring Boot项目中引入依赖

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

父项目依赖

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.1</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

其他依赖可以根据自己使用习惯,不做重点,可基于开发中的项目 

2.注解方式使用Quartz(主要使用@EnableScheduling和 @Scheduled)

@Slf4j
@EnableScheduling
@Configuration
public class DemoQuartz {

    @Scheduled(cron = " 0/5 * * * * ? ")
    public void myLogic1() {
        log.info("调度任务1开始了");
    }

    @Scheduled(cron = " 0/10 * * * * ? ")
    public void myLogic2() {
        log.info("调度任务2开始了");
    }
}

Spring Boot项目中使用Quartz完成定时任务

3.数据库方式使用Quartz(可以动态修改cron表达式/暂停/恢复等操作)

3.1 Mysql数据库中建表

CREATE TABLE demo_quartz_job (
	id VARCHAR(32) PRIMARY KEY COMMENT '主键',
	create_by VARCHAR(32) COMMENT '创建人',
	create_time TIMESTAMP COMMENT '创建时间',
	update_by VARCHAR(32) COMMENT '修改人',
	update_time TIMESTAMP COMMENT '修改时间',
	job_class_name VARCHAR(100) COMMENT '任务类名',
	cron_expression VARCHAR(100) COMMENT 'cron表达式',
	parameter  VARCHAR(100) COMMENT '参数',
	description VARCHAR(100) COMMENT '描述',
	status int(2) COMMENT '状态 0正常-1停止'
) COMMENT = '定时任务表';

3.2 yml配置文件中添加配置

单项目使用配置,不需要创建框架依赖表

spring:
  quartz:
    job-store-type: memory # quartz任务存储类型:jdbc或memory
    wait-for-jobs-to-complete-on-shutdown: true # 关闭时等待任务完成
    overwrite-existing-jobs: true # 可以覆盖已有的任务
    properties: # quartz原生配置
      org:
        quartz:
          scheduler:
            instanceName: scheduler # 调度器实例名称
            instanceId: AUTO # 调度器实例ID自动生成
          jobStore:
            class: org.quartz.simpl.RAMJobStore # RAMJobStore用于存储内存中的调度信息
          threadPool:
            class: org.quartz.simpl.SimpleThreadPool # 指定线程池实现类,对调度器提供固定大小的线程池
            threadCount: 10 # 设置并发线程数量
            threadPriority: 5 # 指定线程优先级

如果要集群配置如下,并且要在数据添加框架依赖表

spring:
  quartz:
    job-store-type: jdbc # quartz任务存储类型:jdbc或memory
    wait-for-jobs-to-complete-on-shutdown: true # 关闭时等待任务完成
    overwrite-existing-jobs: true # 可以覆盖已有的任务
    properties: # quartz原生配置
      org:
        quartz:
          scheduler:
            instanceName: scheduler # 调度器实例名称
            instanceId: AUTO # 调度器实例ID自动生成
          jobStore:
#            class: org.quartz.simpl.RAMJobStore # RAMJobStore用于存储内存中的调度信息
            class: org.quartz.impl.jdbcjobstore.JobStoreTX # 调度信息存储处理类
            driverDelegateClass: org.quartz.impl.jdbcjobstore.StdJDBCDelegate # 使用完全兼容JDBC的驱动
            tablePrefix: QRTZ_ # quartz相关表前缀
            useProperties: false # 是否将JobDataMap中的属性转为字符串存储
          threadPool:
            class: org.quartz.simpl.SimpleThreadPool # 指定线程池实现类,对调度器提供固定大小的线程池
            threadCount: 10 # 设置并发线程数量
            threadPriority: 5 # 指定线程优先级

依赖表脚本

#
# In your Quartz properties file, you'll need to set 
# org.quartz.jobStore.driverDelegateClass = org.quartz.impl.jdbcjobstore.StdJDBCDelegate
#
#
# By: Ron Cordell - roncordell
#  I didn't see this anywhere, so I thought I'd post it here. This is the script from Quartz to create the tables in a MySQL database, modified to use INNODB instead of MYISAM.

DROP TABLE IF EXISTS QRTZ_FIRED_TRIGGERS;
DROP TABLE IF EXISTS QRTZ_PAUSED_TRIGGER_GRPS;
DROP TABLE IF EXISTS QRTZ_SCHEDULER_STATE;
DROP TABLE IF EXISTS QRTZ_LOCKS;
DROP TABLE IF EXISTS QRTZ_SIMPLE_TRIGGERS;
DROP TABLE IF EXISTS QRTZ_SIMPROP_TRIGGERS;
DROP TABLE IF EXISTS QRTZ_CRON_TRIGGERS;
DROP TABLE IF EXISTS QRTZ_BLOB_TRIGGERS;
DROP TABLE IF EXISTS QRTZ_TRIGGERS;
DROP TABLE IF EXISTS QRTZ_JOB_DETAILS;
DROP TABLE IF EXISTS QRTZ_CALENDARS;

CREATE TABLE QRTZ_JOB_DETAILS(
SCHED_NAME VARCHAR(120) NOT NULL,
JOB_NAME VARCHAR(200) NOT NULL,
JOB_GROUP VARCHAR(200) NOT NULL,
DESCRIPTION VARCHAR(250) NULL,
JOB_CLASS_NAME VARCHAR(250) NOT NULL,
IS_DURABLE VARCHAR(1) NOT NULL,
IS_NONCONCURRENT VARCHAR(1) NOT NULL,
IS_UPDATE_DATA VARCHAR(1) NOT NULL,
REQUESTS_RECOVERY VARCHAR(1) NOT NULL,
JOB_DATA BLOB NULL,
PRIMARY KEY (SCHED_NAME,JOB_NAME,JOB_GROUP))
ENGINE=InnoDB;

CREATE TABLE QRTZ_TRIGGERS (
SCHED_NAME VARCHAR(120) NOT NULL,
TRIGGER_NAME VARCHAR(200) NOT NULL,
TRIGGER_GROUP VARCHAR(200) NOT NULL,
JOB_NAME VARCHAR(200) NOT NULL,
JOB_GROUP VARCHAR(200) NOT NULL,
DESCRIPTION VARCHAR(250) NULL,
NEXT_FIRE_TIME BIGINT(13) NULL,
PREV_FIRE_TIME BIGINT(13) NULL,
PRIORITY INTEGER NULL,
TRIGGER_STATE VARCHAR(16) NOT NULL,
TRIGGER_TYPE VARCHAR(8) NOT NULL,
START_TIME BIGINT(13) NOT NULL,
END_TIME BIGINT(13) NULL,
CALENDAR_NAME VARCHAR(200) NULL,
MISFIRE_INSTR SMALLINT(2) NULL,
JOB_DATA BLOB NULL,
PRIMARY KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP),
FOREIGN KEY (SCHED_NAME,JOB_NAME,JOB_GROUP)
REFERENCES QRTZ_JOB_DETAILS(SCHED_NAME,JOB_NAME,JOB_GROUP))
ENGINE=InnoDB;

CREATE TABLE QRTZ_SIMPLE_TRIGGERS (
SCHED_NAME VARCHAR(120) NOT NULL,
TRIGGER_NAME VARCHAR(200) NOT NULL,
TRIGGER_GROUP VARCHAR(200) NOT NULL,
REPEAT_COUNT BIGINT(7) NOT NULL,
REPEAT_INTERVAL BIGINT(12) NOT NULL,
TIMES_TRIGGERED BIGINT(10) NOT NULL,
PRIMARY KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP),
FOREIGN KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP)
REFERENCES QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP))
ENGINE=InnoDB;

CREATE TABLE QRTZ_CRON_TRIGGERS (
SCHED_NAME VARCHAR(120) NOT NULL,
TRIGGER_NAME VARCHAR(200) NOT NULL,
TRIGGER_GROUP VARCHAR(200) NOT NULL,
CRON_EXPRESSION VARCHAR(120) NOT NULL,
TIME_ZONE_ID VARCHAR(80),
PRIMARY KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP),
FOREIGN KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP)
REFERENCES QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP))
ENGINE=InnoDB;

CREATE TABLE QRTZ_SIMPROP_TRIGGERS
  (          
    SCHED_NAME VARCHAR(120) NOT NULL,
    TRIGGER_NAME VARCHAR(200) NOT NULL,
    TRIGGER_GROUP VARCHAR(200) NOT NULL,
    STR_PROP_1 VARCHAR(512) NULL,
    STR_PROP_2 VARCHAR(512) NULL,
    STR_PROP_3 VARCHAR(512) NULL,
    INT_PROP_1 INT NULL,
    INT_PROP_2 INT NULL,
    LONG_PROP_1 BIGINT NULL,
    LONG_PROP_2 BIGINT NULL,
    DEC_PROP_1 NUMERIC(13,4) NULL,
    DEC_PROP_2 NUMERIC(13,4) NULL,
    BOOL_PROP_1 VARCHAR(1) NULL,
    BOOL_PROP_2 VARCHAR(1) NULL,
    PRIMARY KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP),
    FOREIGN KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP) 
    REFERENCES QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP))
ENGINE=InnoDB;

CREATE TABLE QRTZ_BLOB_TRIGGERS (
SCHED_NAME VARCHAR(120) NOT NULL,
TRIGGER_NAME VARCHAR(200) NOT NULL,
TRIGGER_GROUP VARCHAR(200) NOT NULL,
BLOB_DATA BLOB NULL,
PRIMARY KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP),
INDEX (SCHED_NAME,TRIGGER_NAME, TRIGGER_GROUP),
FOREIGN KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP)
REFERENCES QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP))
ENGINE=InnoDB;

CREATE TABLE QRTZ_CALENDARS (
SCHED_NAME VARCHAR(120) NOT NULL,
CALENDAR_NAME VARCHAR(200) NOT NULL,
CALENDAR BLOB NOT NULL,
PRIMARY KEY (SCHED_NAME,CALENDAR_NAME))
ENGINE=InnoDB;

CREATE TABLE QRTZ_PAUSED_TRIGGER_GRPS (
SCHED_NAME VARCHAR(120) NOT NULL,
TRIGGER_GROUP VARCHAR(200) NOT NULL,
PRIMARY KEY (SCHED_NAME,TRIGGER_GROUP))
ENGINE=InnoDB;

CREATE TABLE QRTZ_FIRED_TRIGGERS (
SCHED_NAME VARCHAR(120) NOT NULL,
ENTRY_ID VARCHAR(95) NOT NULL,
TRIGGER_NAME VARCHAR(200) NOT NULL,
TRIGGER_GROUP VARCHAR(200) NOT NULL,
INSTANCE_NAME VARCHAR(200) NOT NULL,
FIRED_TIME BIGINT(13) NOT NULL,
SCHED_TIME BIGINT(13) NOT NULL,
PRIORITY INTEGER NOT NULL,
STATE VARCHAR(16) NOT NULL,
JOB_NAME VARCHAR(200) NULL,
JOB_GROUP VARCHAR(200) NULL,
IS_NONCONCURRENT VARCHAR(1) NULL,
REQUESTS_RECOVERY VARCHAR(1) NULL,
PRIMARY KEY (SCHED_NAME,ENTRY_ID))
ENGINE=InnoDB;

CREATE TABLE QRTZ_SCHEDULER_STATE (
SCHED_NAME VARCHAR(120) NOT NULL,
INSTANCE_NAME VARCHAR(200) NOT NULL,
LAST_CHECKIN_TIME BIGINT(13) NOT NULL,
CHECKIN_INTERVAL BIGINT(13) NOT NULL,
PRIMARY KEY (SCHED_NAME,INSTANCE_NAME))
ENGINE=InnoDB;

CREATE TABLE QRTZ_LOCKS (
SCHED_NAME VARCHAR(120) NOT NULL,
LOCK_NAME VARCHAR(40) NOT NULL,
PRIMARY KEY (SCHED_NAME,LOCK_NAME))
ENGINE=InnoDB;

CREATE INDEX IDX_QRTZ_J_REQ_RECOVERY ON QRTZ_JOB_DETAILS(SCHED_NAME,REQUESTS_RECOVERY);
CREATE INDEX IDX_QRTZ_J_GRP ON QRTZ_JOB_DETAILS(SCHED_NAME,JOB_GROUP);

CREATE INDEX IDX_QRTZ_T_J ON QRTZ_TRIGGERS(SCHED_NAME,JOB_NAME,JOB_GROUP);
CREATE INDEX IDX_QRTZ_T_JG ON QRTZ_TRIGGERS(SCHED_NAME,JOB_GROUP);
CREATE INDEX IDX_QRTZ_T_C ON QRTZ_TRIGGERS(SCHED_NAME,CALENDAR_NAME);
CREATE INDEX IDX_QRTZ_T_G ON QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_GROUP);
CREATE INDEX IDX_QRTZ_T_STATE ON QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_STATE);
CREATE INDEX IDX_QRTZ_T_N_STATE ON QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP,TRIGGER_STATE);
CREATE INDEX IDX_QRTZ_T_N_G_STATE ON QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_GROUP,TRIGGER_STATE);
CREATE INDEX IDX_QRTZ_T_NEXT_FIRE_TIME ON QRTZ_TRIGGERS(SCHED_NAME,NEXT_FIRE_TIME);
CREATE INDEX IDX_QRTZ_T_NFT_ST ON QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_STATE,NEXT_FIRE_TIME);
CREATE INDEX IDX_QRTZ_T_NFT_MISFIRE ON QRTZ_TRIGGERS(SCHED_NAME,MISFIRE_INSTR,NEXT_FIRE_TIME);
CREATE INDEX IDX_QRTZ_T_NFT_ST_MISFIRE ON QRTZ_TRIGGERS(SCHED_NAME,MISFIRE_INSTR,NEXT_FIRE_TIME,TRIGGER_STATE);
CREATE INDEX IDX_QRTZ_T_NFT_ST_MISFIRE_GRP ON QRTZ_TRIGGERS(SCHED_NAME,MISFIRE_INSTR,NEXT_FIRE_TIME,TRIGGER_GROUP,TRIGGER_STATE);

CREATE INDEX IDX_QRTZ_FT_TRIG_INST_NAME ON QRTZ_FIRED_TRIGGERS(SCHED_NAME,INSTANCE_NAME);
CREATE INDEX IDX_QRTZ_FT_INST_JOB_REQ_RCVRY ON QRTZ_FIRED_TRIGGERS(SCHED_NAME,INSTANCE_NAME,REQUESTS_RECOVERY);
CREATE INDEX IDX_QRTZ_FT_J_G ON QRTZ_FIRED_TRIGGERS(SCHED_NAME,JOB_NAME,JOB_GROUP);
CREATE INDEX IDX_QRTZ_FT_JG ON QRTZ_FIRED_TRIGGERS(SCHED_NAME,JOB_GROUP);
CREATE INDEX IDX_QRTZ_FT_T_G ON QRTZ_FIRED_TRIGGERS(SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP);
CREATE INDEX IDX_QRTZ_FT_TG ON QRTZ_FIRED_TRIGGERS(SCHED_NAME,TRIGGER_GROUP);

commit;

3.2 单个任务的添删改成业务代码

业务接口

public interface IDemoQuartzJobService extends IService<DemoQuartzJob> {

    List<DemoQuartzJob> findByJobClassName(String jobClassName);

    Boolean saveAndScheduleJob(DemoQuartzJob quartzJob);

    Boolean editAndScheduleJob(DemoQuartzJob quartzJob) throws SchedulerException;

    Boolean deleteAndStopJob(DemoQuartzJob quartzJob);

    boolean pause(DemoQuartzJob quartzJob);

    boolean resumeJob(DemoQuartzJob quartzJob);

}

业务实现

/**
 * <p>
 * 定时任务表 服务实现类
 * </p>
 *
 */
@Service
public class DemoQuartzJobServiceImpl extends ServiceImpl<DemoQuartzJobMapper, DemoQuartzJob> implements IDemoQuartzJobService {

    @Autowired
    private DemoQuartzJobMapper demoQuartzJobMapper;
    @Autowired
    private Scheduler scheduler;

    /**
     * 正常状态
     */
    public static final Integer STATUS_NORMAL = 0;

    /**
     * 禁用状态
     */
    public static final Integer STATUS_DISABLE = -1;


    @Override
    public List<DemoQuartzJob> findByJobClassName(String jobClassName) {
        return this.demoQuartzJobMapper.findByJobClassName(jobClassName);
    }

    /**
     * 保存&启动定时任务
     */
    @Override
    public Boolean saveAndScheduleJob(DemoQuartzJob quartzJob) {
        if (STATUS_NORMAL.equals(quartzJob.getStatus())) {
            // 定时器添加
            this.schedulerAdd(quartzJob.getJobClassName().trim(), quartzJob.getCronExpression().trim(), quartzJob.getParameter());
        }
        return this.save(quartzJob);
    }

    /**
     * 编辑&启停定时任务
     */
    @Override
    public Boolean editAndScheduleJob(DemoQuartzJob quartzJob) throws SchedulerException {
        if (STATUS_NORMAL.equals(quartzJob.getStatus())) {
            this.schedulerDelete(quartzJob.getJobClassName().trim());
            this.schedulerAdd(quartzJob.getJobClassName().trim(), quartzJob.getCronExpression().trim(), quartzJob.getParameter());
        } else {
            scheduler.pauseJob(JobKey.jobKey(quartzJob.getJobClassName().trim()));
        }
        return this.updateById(quartzJob);
    }

    /**
     * 删除&停止删除定时任务
     */
    @Override
    public Boolean deleteAndStopJob(DemoQuartzJob quartzJob) {
        this.schedulerDelete(quartzJob.getJobClassName().trim());
        return this.removeById(quartzJob.getId());
    }

    /**
     * 暂停任务
     *
     * @return
     */
    @Override
    public boolean pause(DemoQuartzJob quartzJob) {
        this.schedulerDelete(quartzJob.getJobClassName().trim());
        quartzJob.setStatus(STATUS_DISABLE);
        return this.updateById(quartzJob);
    }

    /**
     * 恢复定时任务
     *
     * @return
     */
    @Override
    public boolean resumeJob(DemoQuartzJob quartzJob) {
        this.schedulerDelete(quartzJob.getJobClassName().trim());
        this.schedulerAdd(quartzJob.getJobClassName().trim(), quartzJob.getCronExpression().trim(), quartzJob.getParameter());
        quartzJob.setStatus(STATUS_NORMAL);
        return this.updateById(quartzJob);
    }


    /**
     * 添加定时任务
     *
     * @param jobClassName
     * @param cronExpression cron表达式
     * @param parameter
     */
    private void schedulerAdd(String jobClassName, String cronExpression, String parameter) {
        try {
            // 启动调度器
            scheduler.start();

            // 构建job信息
            JobDetail jobDetail = JobBuilder.newJob(getClass(jobClassName).getClass()).withIdentity(jobClassName).usingJobData("parameter", parameter).build();

            // 表达式调度构建器(即任务执行的时间)
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cronExpression);

            // 按新的cronExpression表达式构建一个新的trigger
            CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(jobClassName).withSchedule(scheduleBuilder).build();

            scheduler.scheduleJob(jobDetail, trigger);
        } catch (SchedulerException e) {
            throw new RuntimeException("创建定时任务失败", e);
        } catch (RuntimeException e) {
            throw new RuntimeException(e.getMessage(), e);
        } catch (Exception e) {
            throw new RuntimeException("后台找不到该类名:" + jobClassName, e);
        }
    }

    /**
     * 删除定时任务
     */
    private void schedulerDelete(String jobClassName) {
        try {
            scheduler.pauseTrigger(TriggerKey.triggerKey(jobClassName));
            scheduler.unscheduleJob(TriggerKey.triggerKey(jobClassName));
            scheduler.deleteJob(JobKey.jobKey(jobClassName));
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new RuntimeException("删除定时任务失败");
        }
    }

    private static Job getClass(String classname) throws Exception {
        Class<?> class1 = Class.forName(classname);
        return (Job) class1.newInstance();
    }
}

controller类

@RestController
@RequestMapping("/quartz")
@Tag(name = "quartz演示controller", description = "定时任务接口")
public class DemoQuartzJobController {

    @Autowired
    private IDemoQuartzJobService demoQuartzJobService;

    @Operation(summary = "添加定时任务接口",description = "添加一个定时任务")
    @PostMapping(value = "/add")
    public ResponseEntity<String> add(@RequestBody DemoQuartzJob quartzJob) {
        try {
            quartzJob.setId(null);
            quartzJob.setStatus(0);
            quartzJob.setCreateTime(LocalDateTime.now());
            List<DemoQuartzJob> list = this.demoQuartzJobService.findByJobClassName(quartzJob.getJobClassName());
            if (list != null && list.size() > 0) {
                return ResponseEntity.ok("该定时任务类名已存在");
            }
            if (this.demoQuartzJobService.saveAndScheduleJob(quartzJob)) {
                return ResponseEntity.ok("创建定时任务成功");
            }
            return ResponseEntity.ok("更新定时任务失败!");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
    }

    @Operation(summary = "修改定时任务接口",description = "修改一个定时任务")
    @PutMapping(value = "/edit")
    public ResponseEntity<?> edit(@RequestBody DemoQuartzJob quartzJob) {

        try {
            quartzJob.setUpdateTime(LocalDateTime.now());
            quartzJob.setStatus(0);
            if (this.demoQuartzJobService.editAndScheduleJob(quartzJob)) {
                return ResponseEntity.ok("更新定时任务成功!");
            }
            return ResponseEntity.ok("更新定时任务失败!");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);

    }

    @Operation(summary = "通过id删除任务接口",description = "通过id删除一个定时任务")
    @DeleteMapping(value = "/delete")
    @Parameter(name = "id",description = "任务ID")
    public ResponseEntity<String> delete(@RequestParam(name = "id", required = true) String id) {
        try {
            DemoQuartzJob quartzJob = this.demoQuartzJobService.getById(id);
            if (quartzJob == null) {
                return ResponseEntity.status(HttpStatus.NO_CONTENT).body("未找到对应实体");
            }
            if (this.demoQuartzJobService.deleteAndStopJob(quartzJob)) {
                return ResponseEntity.ok("删除定时任务成功!");
            } else {
                return ResponseEntity.ok("删除定时任务失败!");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
    }

    @GetMapping(value = "/queryById")
    @Operation(summary = "通过id查询任务接口",description = "通过id查询一个定时任务")
    @Parameter(name = "id",description = "任务ID")
    public ResponseEntity<DemoQuartzJob> queryById(@RequestParam(name = "id", required = true) String id) {
        try {
            DemoQuartzJob quartzJob = this.demoQuartzJobService.getById(id);
            return ResponseEntity.ok(quartzJob);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
    }

    @GetMapping(value = "/pause")
    @Operation(summary = "暂停定时任务接口",description = "暂停一个定时任务")
    @Parameter(name = "jobClassName",description = "任务类名")
    public ResponseEntity<Object> pauseJob(@RequestParam(name = "jobClassName", required = true) String jobClassName) {
        try {
            DemoQuartzJob quartzJob = this.demoQuartzJobService.getOne(new LambdaQueryWrapper<DemoQuartzJob>().eq(DemoQuartzJob::getJobClassName, jobClassName));
            if (quartzJob == null) {
                return ResponseEntity.ok("定时任务不存在!");
            }
            this.demoQuartzJobService.pause(quartzJob);
            return ResponseEntity.ok("暂停定时任务成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
    }

    @GetMapping(value = "/resume")
    @Operation(summary = "启动定时任务接口",description = "启动一个定时任务")
    @Parameter(name = "jobClassName",description = "任务类名")
    public ResponseEntity<Object> resumeJob(@RequestParam(name = "jobClassName", required = true) String jobClassName) {
        try {
            DemoQuartzJob quartzJob = this.demoQuartzJobService.getOne(new LambdaQueryWrapper<DemoQuartzJob>().eq(DemoQuartzJob::getJobClassName, jobClassName));
            if (quartzJob == null) {
                return ResponseEntity.ok("定时任务不存在!");
            }
            this.demoQuartzJobService.resumeJob(quartzJob);
            return ResponseEntity.ok("恢复定时任务成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
    }

}

等会要用到的工作类

public class HelloJob implements Job {

	public void myLogic(){
		SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd hh:mm:ss");
		System.out.println("hello调度程序已执行"+sdf.format(new Date()));
	}

	@Override
	public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
		myLogic();
	}
}

3.3 启动项目测试

通过接口新建一个定时任务

Spring Boot项目中使用Quartz完成定时任务

查看数据库 

Spring Boot项目中使用Quartz完成定时任务

通过接口修改一下

Spring Boot项目中使用Quartz完成定时任务

查看数据库

 Spring Boot项目中使用Quartz完成定时任务

ok,以后如果要添加一个定时任务,只需要在后台新增一个工作类,然后新建一个对应的任务就可以了

 

上一篇:WPF 调试触发器


下一篇:Vue电商后台管理系统部分效果