SpringBoot整合Quartz

本文最后更新于2022.10.11-05:38,某些文章具有时效性,若有错误或已失效,请在下方留言或联系涛哥

什么是Quartz

本意翻译过来叫石英钟

它是一个定时调度任务库

核心组件

  • 调度器:Scheduler
  • 任务:job
  • 触发器:Trigger

cron表达式

3,6,9,12每月1号 6点检查数据库

秒 分钟 小时 日 月 星期 年

0 0 6 1 3,6,9,12 ? *

例子  每个月5号9点执行

0 0 9 5 * ? *

QuickStart

创建job文件夹

SendMsgJob.java

package com.xxgc.helloworld.job;
​
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
​
import java.util.Date;
​
/**
 * @program: helloworld
 * @description: 发送信息的打工人
 * @author: liutao
 * @create: 2022-03-08 19:00
 **/
//alt + enter*3
public class SendMsgJob implements Job {
    //可以在这里做一些资源配置
    private void before(){
        System.out.println("任务开始之前");
    }
    //最终执行方法
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        System.out.println("发送信息:你好"+ new Date());
    }
    //可以在这释放资源
    private void after(){
        System.out.println("任务结束过后");
    }
}

创建scheduler文件夹

QuartzScheduler.java

package com.xxgc.helloworld.scheduler;
​
import com.xxgc.helloworld.job.SendMsgJob;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
​
/**
 * @program: helloword
 * @description: 任务调度器
 * @author: liutao
 * @create: 2022-03-08 19:08
 **/
@Slf4j
@Component
public class QuartzScheduler {
    //工作名
    private static final String JOB_NAME = "msg_report";
    private static final String JOB_GROUP = "msg_report_group";
    //触发器名
    private static final String TRIGGER_NAME = "msg_report";
    private static final String TRIGGER_GROUP = "msg_report_group";
    //工作任务id
    private static final String JOB_TASK_ID = "msg_task_id";
    private SchedulerFactory schedulerFactory= new StdSchedulerFactory();
    /**
     * quartz 任务调度器
     */
//    @Autowired
    private Scheduler scheduler;
    /**
     * 初始化注入一下调度器
     */
    public QuartzScheduler() throws SchedulerException {
        scheduler = schedulerFactory.getScheduler();
    }
​
    /**
     * 开始所有任务的方法
     */
    public void startJob() throws SchedulerException {
        scheduler.start();
    }
​
    public void add(int i,String cron) throws SchedulerException{
        //你想给打工人传的话
        JobDataMap jobDataMap = new JobDataMap();
        jobDataMap.put("msg","好好工作,过年我买大奔");
        // newJob 新建一个工作
        // usingJobData 给工作的打工人传值
        // withIdentity 工作的名称
        JobDetail jobDetail = JobBuilder
                .newJob(SendMsgJob.class)
                .usingJobData(jobDataMap)
                .withIdentity(JOB_NAME + i, JOB_GROUP).build();
        //调度时机  打工时机
        CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(cron);
        // newTrigger 创建一个触发器
        // withIdentity 触发器名
        CronTrigger cronTrigger = TriggerBuilder.newTrigger()
                .withIdentity(TRIGGER_NAME + i, TRIGGER_GROUP)
                .withSchedule(cronScheduleBuilder)
                .build();
        //把打工人和调度器进行绑定
        scheduler.scheduleJob(jobDetail,cronTrigger);
    }
​
    //移除任务  拯救打工人
    public boolean remove(int i) throws SchedulerException{
        boolean b = scheduler.deleteJob(new JobKey(JOB_NAME + i, JOB_GROUP));
        return b;
    }
​
}

项目启动开始打工 

启动入口

package com.xxgc.helloworld.listener;
​
import com.xxgc.helloworld.scheduler.QuartzScheduler;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ContextRefreshedEvent;
​
/**
 * @program: helloworld
 * @description: 项目启动开始打工
 * @author: liutao
 * @create: 2022-03-08 19:51a
 **/
@Configuration
public class QuartzStartListener implements ApplicationListener<ContextRefreshedEvent> {
    @Autowired
    private QuartzScheduler quartzScheduler;
//     项目启动会调用这个方法
    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        try {
            quartzScheduler.startJob();
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }
}

实现案例

1,在pom.xml里导入依赖配置

  <!--任务调度器-->
        <dependency>
            <groupId>org.quartz-scheduler</groupId>
            <artifactId>quartz</artifactId>
        </dependency>

2,导入数据库表

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,在application.yml里进行配置

#quartz的持久化配置
  quartz:
    #相关属性配置
    properties:
      org:
        quartz:
          scheduler:
            instanceName: quartzScheduler
            instanceId: AUTO
          jobStore:
            class: org.quartz.impl.jdbcjobstore.JobStoreTX
            driverDelegateClass: org.quartz.impl.jdbcjobstore.StdJDBCDelegate
            tablePrefix: QRTZ_
            isClustered: false
            clusterCheckinInterval: 10000
            useProperties: false
            dataSource: quartzDs
          threadPool:
            class: org.quartz.simpl.SimpleThreadPool
            threadCount: 10
            threadPriority: 5
            threadsInheritContextClassLoaderOfInitializingThread: true
    #数据库方式
    job-store-type: JDBC
    #初始化表结构
    jdbc:
      initialize-schema: NEVER
        #数据源配置
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/springboot-study?useUnicode=true&amp;characterEncoding=UTF-8
    username: root
    password: 123456

4,创建job文件夹创建一个job

SendMsgJob.java

package com.xxgc.helloworld.job;
​
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
​
import java.util.Date;
​
/**
 * @program: helloworld
 * @description: 发送信息的打工人
 * @author: liutao
 * @create: 2022-03-08 19:00
 **/
//alt + enter*3
public class SendMsgJob implements Job {
    //可以在这里做一些资源配置
    private void before(){
        System.out.println("任务开始之前");
    }
    //最终执行方法
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        System.out.println("发送信息:你好"+ new Date());
    }
    //可以在这释放资源
    private void after(){
        System.out.println("任务结束过后");
    }
} ​

5,创建config文件夹添加以下文件

QuartzStartListener.java

package com.xxgc.helloworld.config;
​
import com.xxgc.helloworld.scheduler.QuartzScheduler;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ContextRefreshedEvent;
​
/**
 * @program: helloworld
 * @description: 项目启动开始打工
 * @author: liutao
 * @create: 2022-03-08 19:51a
 **/
@Configuration
public class QuartzStartListener implements ApplicationListener<ContextRefreshedEvent> {
    @Autowired
    private QuartzScheduler quartzScheduler;
//     项目启动会调用这个方法
    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        try {
            quartzScheduler.startJob();
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }
}
 

5,创建一个utils文件夹添加以下文件
QuartzManagerUtils.java

package com.xxgc.helloworld.utils;
​
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
​
import java.util.Map;
​
/**
 * @program: helloword
 * @description: 任务调度器工具类
 * @author: liutao
 * @create: 2022-03-08 21:03
 **/
public class QuartzManagerUtils {
    private static SchedulerFactory gSchedulerFactory = new StdSchedulerFactory();  //创建一个SchedulerFactory工厂实例
    private static final String JOB_GROUP_NAME = "FH_JOBGROUP_NAME";                      //任务组
    private static final String TRIGGER_GROUP_NAME = "FH_TRIGGERGROUP_NAME";              //触发器组
​
    /**添加一个定时任务,使用默认的任务组名,触发器名,触发器组名
     * @param jobName 任务名
     * @param cls 任务
     * @param time 时间设置,参考quartz说明文档
     */
    public static void addJob(String jobName, Class<? extends Job> cls, String time) {
        try {
            Scheduler sched = gSchedulerFactory.getScheduler();                                         //通过SchedulerFactory构建Scheduler对象
            JobDetail jobDetail= JobBuilder.newJob(cls).withIdentity(jobName,JOB_GROUP_NAME).build();   //用于描叙Job实现类及其他的一些静态信息,构建一个作业实例
            CronTrigger trigger = (CronTrigger) TriggerBuilder
                    .newTrigger()                                                                       //创建一个新的TriggerBuilder来规范一个触发器
                    .withIdentity(jobName, TRIGGER_GROUP_NAME)                                          //给触发器起一个名字和组名
                    .withSchedule(CronScheduleBuilder.cronSchedule(time))
                    .build();
            sched.scheduleJob(jobDetail, trigger);
            if (!sched.isShutdown()) {
                sched.start();        // 启动
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
​
    /**添加一个定时任务,使用默认的任务组名,触发器名,触发器组名  (带参数)
     * @param jobName 任务名
     * @param cls 任务
     * @param time 时间设置,参考quartz说明文档
     */
    public static void addJob(String jobName, Class<? extends Job> cls, String time, Map<String,Object> parameter) {
        try {
            Scheduler sched = gSchedulerFactory.getScheduler();                                         //通过SchedulerFactory构建Scheduler对象
            JobDetail jobDetail= JobBuilder.newJob(cls).withIdentity(jobName,JOB_GROUP_NAME).build();   //用于描叙Job实现类及其他的一些静态信息,构建一个作业实例
            jobDetail.getJobDataMap().put("parameterList", parameter);                                  //传参数
            CronTrigger trigger = (CronTrigger) TriggerBuilder
                    .newTrigger()                                                                       //创建一个新的TriggerBuilder来规范一个触发器
                    .withIdentity(jobName, TRIGGER_GROUP_NAME)                                          //给触发器起一个名字和组名
                    .withSchedule(CronScheduleBuilder.cronSchedule(time))
                    .build();
            sched.scheduleJob(jobDetail, trigger);
            if (!sched.isShutdown()) {
                sched.start();        // 启动
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
​
    /**添加一个定时任务
     * @param jobName   任务名
     * @param jobGroupName  任务组名
     * @param triggerName   触发器名
     * @param triggerGroupName  触发器组名
     * @param jobClass  任务
     * @param time  时间设置,参考quartz说明文档
     */
    public static void addJob(String jobName, String jobGroupName,
                              String triggerName, String triggerGroupName, Class<? extends Job> jobClass,
                              String time) {
        try {
            Scheduler sched = gSchedulerFactory.getScheduler();
            JobDetail jobDetail= JobBuilder.newJob(jobClass).withIdentity(jobName,jobGroupName).build();// 任务名,任务组,任务执行类
            CronTrigger trigger = (CronTrigger) TriggerBuilder   // 触发器
                    .newTrigger()
                    .withIdentity(triggerName, triggerGroupName)
                    .withSchedule(CronScheduleBuilder.cronSchedule(time))
                    .build();
            sched.scheduleJob(jobDetail, trigger);
            if (!sched.isShutdown()) {
                sched.start();        // 启动
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
​
    /**添加一个定时任务  (带参数)
     * @param jobName   任务名
     * @param jobGroupName  任务组名
     * @param triggerName   触发器名
     * @param triggerGroupName  触发器组名
     * @param jobClass  任务
     * @param time  时间设置,参考quartz说明文档
     */
    public static void addJob(String jobName, String jobGroupName,
                              String triggerName, String triggerGroupName, Class<? extends Job> jobClass,
                              String time, Map<String,Object> parameter) {
        try {
            Scheduler sched = gSchedulerFactory.getScheduler();
            JobDetail jobDetail= JobBuilder.newJob(jobClass).withIdentity(jobName,jobGroupName).build();// 任务名,任务组,任务执行类
            jobDetail.getJobDataMap().put("parameterList", parameter);                              //传参数
            CronTrigger trigger = (CronTrigger) TriggerBuilder   // 触发器
                    .newTrigger()
                    .withIdentity(triggerName, triggerGroupName)
                    .withSchedule(CronScheduleBuilder.cronSchedule(time))
                    .build();
            sched.scheduleJob(jobDetail, trigger);
            if (!sched.isShutdown()) {
                sched.start();        // 启动
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
​
    /** 修改一个任务的触发时间(使用默认的任务组名,触发器名,触发器组名)
     * @param jobName   任务名
     * @param time  新的时间设置
     */
    public static void modifyJobTime(String jobName, String time) {
        try {
            Scheduler sched = gSchedulerFactory.getScheduler();                             //通过SchedulerFactory构建Scheduler对象
            TriggerKey triggerKey = TriggerKey.triggerKey(jobName,TRIGGER_GROUP_NAME);      //通过触发器名和组名获取TriggerKey
            CronTrigger trigger = (CronTrigger)sched.getTrigger(triggerKey);                //通过TriggerKey获取CronTrigger
            if (trigger == null) {
                return;
            }
            String oldTime = trigger.getCronExpression();
            if (!oldTime.equalsIgnoreCase(time)) {
                JobKey jobKey = JobKey.jobKey(jobName, JOB_GROUP_NAME);                     //通过任务名和组名获取JobKey
                JobDetail jobDetail = sched.getJobDetail(jobKey);
                Class<? extends Job> objJobClass = jobDetail.getJobClass();
                removeJob(jobName);
                addJob(jobName, objJobClass, time);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
​
    /**修改一个任务的触发时间
     * @param triggerName   任务名称
     * @param triggerGroupName  传过来的任务名称
     * @param time  更新后的时间规则
     */
    public static void modifyJobTime(String triggerName, String triggerGroupName, String time) {
        try {
            Scheduler sched = gSchedulerFactory.getScheduler();                             //通过SchedulerFactory构建Scheduler对象
            TriggerKey triggerKey = TriggerKey.triggerKey(triggerName,triggerGroupName);    //通过触发器名和组名获取TriggerKey
            CronTrigger trigger = (CronTrigger)sched.getTrigger(triggerKey);                //通过TriggerKey获取CronTrigger
            if (trigger == null)  return;
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(trigger.getCronExpression());
            String oldTime = trigger.getCronExpression();
            if (!oldTime.equalsIgnoreCase(time)) {
                trigger = (CronTrigger)trigger.getTriggerBuilder()      //重新构建trigger
                        .withIdentity(triggerKey)
                        .withSchedule(scheduleBuilder)
                        .withSchedule(CronScheduleBuilder.cronSchedule(time))
                        .build();
                sched.rescheduleJob(triggerKey, trigger);               //按新的trigger重新设置job执行
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
​
    /**移除一个任务(使用默认的任务组名,触发器名,触发器组名)
     * @param jobName   任务名称
     */
    public static void removeJob(String jobName) {
        try {
            Scheduler sched = gSchedulerFactory.getScheduler();
            TriggerKey triggerKey = TriggerKey.triggerKey(jobName,TRIGGER_GROUP_NAME);  //通过触发器名和组名获取TriggerKey
            JobKey jobKey = JobKey.jobKey(jobName, JOB_GROUP_NAME);                     //通过任务名和组名获取JobKey
            sched.pauseTrigger(triggerKey); // 停止触发器
            sched.unscheduleJob(triggerKey);// 移除触发器
            sched.deleteJob(jobKey);        // 删除任务
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
​
    /**移除一个任务
     * @param jobName   任务名
     * @param jobGroupName  任务组名
     * @param triggerName   触发器名
     * @param triggerGroupName  触发器组名
     */
    public static void removeJob(String jobName, String jobGroupName,String triggerName, String triggerGroupName) {
        try {
            Scheduler sched = gSchedulerFactory.getScheduler();
            TriggerKey triggerKey = TriggerKey.triggerKey(triggerName,triggerGroupName);    //通过触发器名和组名获取TriggerKey
            JobKey jobKey = JobKey.jobKey(jobName, jobGroupName);                           //通过任务名和组名获取JobKey
            sched.pauseTrigger(triggerKey); // 停止触发器
            sched.unscheduleJob(triggerKey);// 移除触发器
            sched.deleteJob(jobKey);        // 删除任务
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
​
    /**
     * 启动所有定时任务
     */
    public static void startJobs() {
        try {
            Scheduler sched = gSchedulerFactory.getScheduler();
            sched.start();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
​
    /**
     * 关闭所有定时任务
     */
    public static void shutdownJobs() {
        try {
            Scheduler sched = gSchedulerFactory.getScheduler();
            if (!sched.isShutdown()) {
                sched.shutdown();
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

6,使用

QuartzScheduler.java

 @Test
    public void test1() throws SchedulerException, InterruptedException {
        /*  2022年 3月 8日 20时 20分 0秒开始 每5秒执行一次  */
        QuartzManagerUtils.addJob("打工仔", SendMsgJob.class,"0/3 * * * * ? *");
        Thread.sleep(500000);
    }

 效果

阅读剩余
THE END