springboot+quartz实现动态任务管理,携带参数. 使用druid连接mysql数据库持久化.完整代码,有问题留言一起探讨

1.添加依赖

        
        
            org.springframework.boot
            spring-boot-starter-quartz
        
        
        
            com.alibaba
            druid
            1.1.9
        
        
		
			mysql
			mysql-connector-java
			runtime
		

2.quartz配置文件quartz.properties, 放在resource下

#org.quartz.scheduler.instanceName = MyScheduler
org.quartz.threadPool.threadCount = 5
org.quartz.jobStore.class = org.quartz.impl.jdbcjobstore.JobStoreTX
org.quartz.jobStore.driverDelegateClass = org.quartz.impl.jdbcjobstore.StdJDBCDelegate
org.quartz.jobStore.tablePrefix = QRTZ_
org.quartz.jobStore.dataSource = myDS
#这个类下一步写,写好了把全类名复制过来
org.quartz.dataSource.myDS.connectionProvider.class:com.example.demo_quartz.config.DruidConnectionProvider
org.quartz.dataSource.myDS.driver = com.mysql.cj.jdbc.Driver
org.quartz.dataSource.myDS.URL = 你的数据库URL
org.quartz.dataSource.myDS.user = 你的数据库用户名
org.quartz.dataSource.myDS.password = 你的数据库密码
org.quartz.dataSource.myDS.maxConnection = 5

3.新建config包(这个随意),新建Druid连接池的Quartz扩展类DruidConnectionProvider

//包名没有复制
import com.alibaba.druid.pool.DruidDataSource;
import org.quartz.SchedulerException;
import org.quartz.utils.ConnectionProvider;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * [Druid连接池的Quartz扩展类]
 */
public class DruidConnectionProvider implements ConnectionProvider {


    /**
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     *
     * 常量配置,与quartz.properties文件的key保持一致(去掉前缀),同时提供set方法,Quartz框架自动注入值。
     *
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     */
    //JDBC驱动
    public String driver;
    //JDBC连接串
    public String URL;
    //数据库用户名
    public String user;
    //数据库用户密码
    public String password;
    //数据库最大连接数
    public int maxConnection;
    //数据库SQL查询每次连接返回执行到连接池,以确保它仍然是有效的。
    public String validationQuery;
    private boolean validateOnCheckout;
    private int idleConnectionValidationSeconds;
    public String maxCachedStatementsPerConnection;
    private String discardIdleConnectionsSeconds;
    public static final int DEFAULT_DB_MAX_CONNECTIONS = 10;
    public static final int DEFAULT_DB_MAX_CACHED_STATEMENTS_PER_CONNECTION = 120;
    //Druid连接池
    private DruidDataSource quartzDatasource;

    /**
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     *
     * 接口实现
     *
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     */
    @Override
    public Connection getConnection() throws SQLException {
        return quartzDatasource.getConnection();
    }

    @Override
    public void shutdown() throws SQLException {
        quartzDatasource.close();
    }

    @Override
    public void initialize() throws SQLException {
        if (this.URL == null) {
            throw new SQLException("DBPool could not be created: DB URL cannot be null");
        }
        if (this.driver == null) {
            throw new SQLException("DBPool driver could not be created: DB driver class name cannot be null!");
        }
        if (this.maxConnection < 0) {
            throw new SQLException("DBPool maxConnectins could not be created: Max connections must be greater than zero!");
        }
        quartzDatasource = new DruidDataSource();
        try{
            quartzDatasource.setDriverClassName(this.driver);
        } catch (Exception e) {
            try {
                throw new SchedulerException("Problem setting driver class name on datasource: " + e.getMessage(), e);
            } catch (SchedulerException e1) {
            }
        }

        quartzDatasource.setUrl(this.URL);
        quartzDatasource.setUsername(this.user);
        quartzDatasource.setPassword(this.password);
        quartzDatasource.setMaxActive(this.maxConnection);
        quartzDatasource.setMinIdle(1);
        quartzDatasource.setMaxWait(0);
        quartzDatasource.setMaxPoolPreparedStatementPerConnectionSize(DEFAULT_DB_MAX_CONNECTIONS);
        if (this.validationQuery != null) {
            quartzDatasource.setValidationQuery(this.validationQuery);
            if(!this.validateOnCheckout)
                quartzDatasource.setTestOnReturn(true);
            else
                quartzDatasource.setTestOnBorrow(true);
            quartzDatasource.setValidationQueryTimeout(this.idleConnectionValidationSeconds);
        }
    }

    /*
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     *
     * 提供get set方法
     *
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     */
    public String getDriver() {
        return driver;
    }
    public void setDriver(String driver) {
        this.driver = driver;
    }
    public String getURL() {
        return URL;
    }
    public void setURL(String URL) {
        this.URL = URL;
    }
    public String getUser() {
        return user;
    }
    public void setUser(String user) {
        this.user = user;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public int getMaxConnection() {
        return maxConnection;
    }
    public void setMaxConnection(int maxConnection) {
        this.maxConnection = maxConnection;
    }
    public String getValidationQuery() {
        return validationQuery;
    }
    public void setValidationQuery(String validationQuery) {
        this.validationQuery = validationQuery;
    }
    public boolean isValidateOnCheckout() {
        return validateOnCheckout;
    }
    public void setValidateOnCheckout(boolean validateOnCheckout) {
        this.validateOnCheckout = validateOnCheckout;
    }
    public int getIdleConnectionValidationSeconds() {
        return idleConnectionValidationSeconds;
    }
    public void setIdleConnectionValidationSeconds(int idleConnectionValidationSeconds) {
        this.idleConnectionValidationSeconds = idleConnectionValidationSeconds;
    }
    public DruidDataSource getDatasource() {
        return quartzDatasource;
    }
    public void setDatasource(DruidDataSource datasource) {
        this.quartzDatasource = datasource;
    }
    public String getDiscardIdleConnectionsSeconds() {
        return discardIdleConnectionsSeconds;
    }
    public void setDiscardIdleConnectionsSeconds(String discardIdleConnectionsSeconds) {
        this.discardIdleConnectionsSeconds = discardIdleConnectionsSeconds;
    }


}

4.在使用quartz做持久化的时候需要用到quartz的11张表,可以去quartz官网下载对应版本的quartz,解压打开docs/dbTables里面有对应数据库的建表语句。关于quartz.properties配置的详细解释可以查看quartz官网。另外新建一张表APP_QUARTZ用于存放定时任务基本信息和描述等信息,定时任务的增、删、改、执行等功能与此表没有任何关系。

springboot+quartz实现动态任务管理,携带参数. 使用druid连接mysql数据库持久化.完整代码,有问题留言一起探讨_第1张图片

我的sql建表

/*
Navicat MySQL Data Transfer

Source Server         : local
Source Server Version : 50527
Source Host           : localhost:3306
Source Database       : quartz

Target Server Type    : MYSQL
Target Server Version : 50527
File Encoding         : 65001

Date: 2019-09-04 17:02:10
*/

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) NOT NULL,
  `TRIGGER_NAME` varchar(200) NOT NULL,
  `TRIGGER_GROUP` varchar(200) NOT NULL,
  `BLOB_DATA` blob,
  PRIMARY KEY (`SCHED_NAME`,`TRIGGER_NAME`,`TRIGGER_GROUP`),
  CONSTRAINT `QRTZ_BLOB_TRIGGERS_ibfk_1` FOREIGN KEY (`SCHED_NAME`, `TRIGGER_NAME`, `TRIGGER_GROUP`) REFERENCES `qrtz_triggers` (`SCHED_NAME`, `TRIGGER_NAME`, `TRIGGER_GROUP`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

-- ----------------------------
-- Records of qrtz_blob_triggers
-- ----------------------------

-- ----------------------------
-- Table structure for `qrtz_calendars`
-- ----------------------------
DROP TABLE IF EXISTS `qrtz_calendars`;
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 DEFAULT CHARSET=latin1;

-- ----------------------------
-- Records of qrtz_calendars
-- ----------------------------

-- ----------------------------
-- Table structure for `qrtz_cron_triggers`
-- ----------------------------
DROP TABLE IF EXISTS `qrtz_cron_triggers`;
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(200) NOT NULL,
  `TIME_ZONE_ID` varchar(80) DEFAULT NULL,
  PRIMARY KEY (`SCHED_NAME`,`TRIGGER_NAME`,`TRIGGER_GROUP`),
  CONSTRAINT `QRTZ_CRON_TRIGGERS_ibfk_1` FOREIGN KEY (`SCHED_NAME`, `TRIGGER_NAME`, `TRIGGER_GROUP`) REFERENCES `qrtz_triggers` (`SCHED_NAME`, `TRIGGER_NAME`, `TRIGGER_GROUP`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

-- ----------------------------
-- Records of qrtz_cron_triggers
-- ----------------------------

-- ----------------------------
-- Table structure for `qrtz_fired_triggers`
-- ----------------------------
DROP TABLE IF EXISTS `qrtz_fired_triggers`;
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` int(11) NOT NULL,
  `STATE` varchar(16) NOT NULL,
  `JOB_NAME` varchar(200) DEFAULT NULL,
  `JOB_GROUP` varchar(200) DEFAULT NULL,
  `IS_NONCONCURRENT` varchar(1) DEFAULT NULL,
  `REQUESTS_RECOVERY` varchar(1) DEFAULT NULL,
  PRIMARY KEY (`SCHED_NAME`,`ENTRY_ID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

-- ----------------------------
-- Records of qrtz_fired_triggers
-- ----------------------------

-- ----------------------------
-- Table structure for `qrtz_job_details`
-- ----------------------------
DROP TABLE IF EXISTS `qrtz_job_details`;
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) DEFAULT 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,
  PRIMARY KEY (`SCHED_NAME`,`JOB_NAME`,`JOB_GROUP`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

-- ----------------------------
-- Records of qrtz_job_details
-- ----------------------------

-- ----------------------------
-- Table structure for `qrtz_locks`
-- ----------------------------
DROP TABLE IF EXISTS `qrtz_locks`;
CREATE TABLE `qrtz_locks` (
  `SCHED_NAME` varchar(120) NOT NULL,
  `LOCK_NAME` varchar(40) NOT NULL,
  PRIMARY KEY (`SCHED_NAME`,`LOCK_NAME`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

-- ----------------------------
-- Records of qrtz_locks
-- ----------------------------

-- ----------------------------
-- 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) NOT NULL,
  `TRIGGER_GROUP` varchar(200) NOT NULL,
  PRIMARY KEY (`SCHED_NAME`,`TRIGGER_GROUP`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

-- ----------------------------
-- Records of qrtz_paused_trigger_grps
-- ----------------------------

-- ----------------------------
-- Table structure for `qrtz_scheduler_state`
-- ----------------------------
DROP TABLE IF EXISTS `qrtz_scheduler_state`;
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 DEFAULT CHARSET=latin1;

-- ----------------------------
-- Records of qrtz_scheduler_state
-- ----------------------------

-- ----------------------------
-- Table structure for `qrtz_simple_triggers`
-- ----------------------------
DROP TABLE IF EXISTS `qrtz_simple_triggers`;
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`),
  CONSTRAINT `QRTZ_SIMPLE_TRIGGERS_ibfk_1` FOREIGN KEY (`SCHED_NAME`, `TRIGGER_NAME`, `TRIGGER_GROUP`) REFERENCES `qrtz_triggers` (`SCHED_NAME`, `TRIGGER_NAME`, `TRIGGER_GROUP`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

-- ----------------------------
-- Records of qrtz_simple_triggers
-- ----------------------------

-- ----------------------------
-- Table structure for `qrtz_simprop_triggers`
-- ----------------------------
DROP TABLE IF EXISTS `qrtz_simprop_triggers`;
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) DEFAULT NULL,
  `STR_PROP_2` varchar(512) DEFAULT NULL,
  `STR_PROP_3` varchar(512) DEFAULT NULL,
  `INT_PROP_1` int(11) DEFAULT NULL,
  `INT_PROP_2` int(11) DEFAULT NULL,
  `LONG_PROP_1` bigint(20) DEFAULT NULL,
  `LONG_PROP_2` bigint(20) DEFAULT NULL,
  `DEC_PROP_1` decimal(13,4) DEFAULT NULL,
  `DEC_PROP_2` decimal(13,4) DEFAULT NULL,
  `BOOL_PROP_1` varchar(1) DEFAULT NULL,
  `BOOL_PROP_2` varchar(1) DEFAULT NULL,
  PRIMARY KEY (`SCHED_NAME`,`TRIGGER_NAME`,`TRIGGER_GROUP`),
  CONSTRAINT `QRTZ_SIMPROP_TRIGGERS_ibfk_1` FOREIGN KEY (`SCHED_NAME`, `TRIGGER_NAME`, `TRIGGER_GROUP`) REFERENCES `qrtz_triggers` (`SCHED_NAME`, `TRIGGER_NAME`, `TRIGGER_GROUP`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

-- ----------------------------
-- Records of qrtz_simprop_triggers
-- ----------------------------

-- ----------------------------
-- Table structure for `qrtz_triggers`
-- ----------------------------
DROP TABLE IF EXISTS `qrtz_triggers`;
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) DEFAULT NULL,
  `NEXT_FIRE_TIME` bigint(13) DEFAULT NULL,
  `PREV_FIRE_TIME` bigint(13) DEFAULT NULL,
  `PRIORITY` int(11) DEFAULT NULL,
  `TRIGGER_STATE` varchar(16) NOT NULL,
  `TRIGGER_TYPE` varchar(8) NOT NULL,
  `START_TIME` bigint(13) NOT NULL,
  `END_TIME` bigint(13) DEFAULT NULL,
  `CALENDAR_NAME` varchar(200) DEFAULT NULL,
  `MISFIRE_INSTR` smallint(2) DEFAULT NULL,
  `JOB_DATA` blob,
  PRIMARY KEY (`SCHED_NAME`,`TRIGGER_NAME`,`TRIGGER_GROUP`),
  KEY `SCHED_NAME` (`SCHED_NAME`,`JOB_NAME`,`JOB_GROUP`),
  CONSTRAINT `QRTZ_TRIGGERS_ibfk_1` FOREIGN KEY (`SCHED_NAME`, `JOB_NAME`, `JOB_GROUP`) REFERENCES `qrtz_job_details` (`SCHED_NAME`, `JOB_NAME`, `JOB_GROUP`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

-- ----------------------------
-- Records of qrtz_triggers
-- ----------------------------

quartz任务信息表

DROP TABLE IF EXISTS `sys_quartz`;
CREATE TABLE `sys_quartz` (
  `id` int(255) NOT NULL,
  `job_type` varchar(255) DEFAULT NULL,
  `job_name` varchar(255) NOT NULL,
  `job_classname` varchar(255) NOT NULL,
  `job_group` varchar(255) NOT NULL,
  `time_type` int(255) NOT NULL,
  `cron_expression` varchar(255) NOT NULL,
  `invoke_param` varchar(255) NOT NULL
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='quartz任务信息表';

quartz任务信息实体, 注意jobClassname的get方法

package com.example.demo_quartz.pojo;


public class AppQuartz {
    private Integer quartzId;       //id  主键
    private String jobName;         //任务名称
    private String jobClassname;    //执行任务逻辑那个类名
    private String jobGroup;        //任务分组
    private String jobType;         //任务类型
    private Integer timeType;       //时间类型
    private String cronExpression;  //corn表达式
    private Integer invokeParam;//需要传递的参数

    public AppQuartz() {
    }

    public AppQuartz(Integer quartzId, String jobName, String jobClassname, String jobGroup, String jobType, Integer timeType, String cronExpression, Integer invokeParam) {
        this.quartzId = quartzId;
        this.jobName = jobName;
        this.jobClassname = jobClassname;
        this.jobGroup = jobGroup;
        this.jobType = jobType;
        this.timeType = timeType;
        this.cronExpression = cronExpression;
        this.invokeParam = invokeParam;
    }

//后面要用到
    public String getJobClassname() {
        return "com.example.demo_quartz.job_group."+ jobClassname;
    }

    public void setJobClassname(String jobClassname) {
        this.jobClassname = jobClassname;
    }

    public String getJobType() {
        return jobType;
    }

    public void setJobType(String jobType) {
        this.jobType = jobType;
    }

    public Integer getTimeType() {
        return timeType;
    }

    public void setTimeType(Integer timeType) {
        this.timeType = timeType;
    }

    public Integer getQuartzId() {
        return quartzId;
    }

    public void setQuartzId(Integer quartzId) {
        this.quartzId = quartzId;
    }

    public String getJobName() {
        return jobName;
    }

    public void setJobName(String jobName) {
        this.jobName = jobName;
    }

    public String getJobGroup() {
        return jobGroup;
    }

    public void setJobGroup(String jobGroup) {
        this.jobGroup = jobGroup;
    }

    public String getCronExpression() {
        return cronExpression;
    }

    public void setCronExpression(String cronExpression) {
        this.cronExpression = cronExpression;
    }

    public Integer getInvokeParam() {
        return invokeParam;
    }

    public void setInvokeParam(Integer invokeParam) {
        this.invokeParam = invokeParam;
    }

    @Override
    public String toString() {
        return "AppQuartz{" +
                "quartzId=" + quartzId +
                ", jobName='" + jobName + '\'' +
                ", jobClassname='" + jobClassname + '\'' +
                ", jobGroup='" + jobGroup + '\'' +
                ", jobType='" + jobType + '\'' +
                ", timeType=" + timeType +
                ", cronExpression='" + cronExpression + '\'' +
                ", invokeParam=" + invokeParam +
                '}';
    }
}

5.Quartz配置类

import org.quartz.Scheduler;
import org.quartz.ee.servlet.QuartzInitializerListener;
import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

import java.io.IOException;
import java.util.Properties;

@Configuration
public class SchedulerConfig {


    @Bean(name="SchedulerFactory")
    public SchedulerFactoryBean schedulerFactoryBean() throws IOException {
        SchedulerFactoryBean factory = new SchedulerFactoryBean();

        factory.setQuartzProperties(quartzProperties());

        return factory;
    }

    @Bean
    public Properties quartzProperties() throws IOException {
        PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
        propertiesFactoryBean.setLocation(new ClassPathResource("/quartz.properties"));
        //在quartz.properties中的属性被读取并注入后再初始化对象
        propertiesFactoryBean.afterPropertiesSet();
        return propertiesFactoryBean.getObject();
    }

    /**
     * quartz初始化监听器
     * 这个监听器可以监听到工程的启动,在工程停止再启动时可以让已有的定时任务继续进行。
     * @return
     */
    @Bean
    public QuartzInitializerListener executorListener() {
        return new QuartzInitializerListener();
    }

    /**
     *
     *通过SchedulerFactoryBean获取Scheduler的实例
     */

    @Bean(name="Scheduler")
    public Scheduler scheduler() throws IOException {
        return schedulerFactoryBean().getScheduler();
    }

}

6.创建定时任务服务和定时任务分组类(具体的业务逻辑实现写在这个类)

package com.example.demo_quartz.job_group;


import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

/**
 * jobGroup基础接口,自己实现业务逻辑的job类都要实现这个借口
 * 创建任务时要用
 */
public interface BaseJob extends Job {

    public void execute(JobExecutionContext context) throws JobExecutionException;
}

package com.example.demo_quartz.job_group;

import org.quartz.*;

@PersistJobDataAfterExecution
@DisallowConcurrentExecution
public class JobOne implements BaseJob{
    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        JobDataMap data=context.getTrigger().getJobDataMap();
        Integer invokeParam = (Integer) data.get("invokeParam");
        //在这里实现业务逻辑
        System.out.println("JobOne开始运行,任务参数是:" + invokeParam);
    }
}

package com.example.demo_quartz.job_group;

import org.quartz.*;
import org.springframework.stereotype.Component;

@PersistJobDataAfterExecution
@DisallowConcurrentExecution
@Component
public class JobTwo implements BaseJob{
    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        JobDataMap data=context.getTrigger().getJobDataMap();
        Integer invokeParam = (Integer) data.get("invokeParam");
        //在这里实现业务逻辑
        System.out.println("JobTwo开始运行,任务参数是:" + invokeParam);
    }
}

package com.example.demo_quartz.service;

import com.example.demo_quartz.job_group.BaseJob;
import com.example.demo_quartz.pojo.AppQuartz;
import com.example.demo_quartz.util.DateUnit;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import static org.quartz.DateBuilder.futureDate;

@Service
public class QuartzService {


    @Autowired
    @Qualifier("Scheduler")
    private Scheduler scheduler;

    @Autowired
    private DateUnit dateUnit;

    /**
     * 新建一个任务
     *
     */
    public String addJob(AppQuartz appQuartz) throws Exception  {
        if ("".equals(appQuartz.getJobGroup()) || "".equals(appQuartz.getJobName()) || "".equals(appQuartz.getJobClassname()) || "".equals(appQuartz.getCronExpression())) {
            return "没有接收到参数,请检查";
        }
        if (appQuartz.getTimeType() == null) {
            return addCronJob(appQuartz);
        }
        return addSimpleJob(appQuartz);
    }

    //CronTrigger
    public String addCronJob(AppQuartz appQuartz) throws Exception {

        // 启动调度器
        scheduler.start();

        //构建job信息
        JobDetail jobDetail = JobBuilder.newJob(getClass(appQuartz.getJobClassname().trim()).getClass()).
                withIdentity(appQuartz.getJobClassname(), appQuartz.getJobGroup())
                .build();

        //表达式调度构建器(即任务执行的时间)
        CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(appQuartz.getCronExpression());
        //按新的cronExpression表达式构建一个新的trigger
        CronTrigger trigger = TriggerBuilder.newTrigger().
                withIdentity(appQuartz.getJobClassname(), appQuartz.getJobGroup())
                .withSchedule(scheduleBuilder)
                .build();

        //传递参数
        if(appQuartz.getInvokeParam()!=null && !"".equals(appQuartz.getInvokeParam())) {
            trigger.getJobDataMap().put("invokeParam",appQuartz.getInvokeParam());
        }
        try {
            scheduler.scheduleJob(jobDetail, trigger);
            return "success";
        } catch (SchedulerException e) {
            System.out.println("创建定时任务失败" + e);
            return e.getMessage();
        }
    }

    //Simple Trigger
    public String addSimpleJob(AppQuartz appQuartz) throws Exception {
        // 启动调度器
        scheduler.start();

        //构建job信息
        JobDetail jobDetail = JobBuilder.newJob(getClass(appQuartz.getJobClassname().trim()).getClass())
                .withIdentity(appQuartz.getJobGroup(), appQuartz.getJobName())
                .build();

        DateBuilder.IntervalUnit verDate = dateUnit.verification(appQuartz.getTimeType());
        SimpleTrigger simpleTrigger = (SimpleTrigger) TriggerBuilder.newTrigger()
                .withIdentity(appQuartz.getJobClassname(), appQuartz.getJobGroup())
                .startAt(futureDate(Integer.parseInt(appQuartz.getCronExpression()), verDate))
                .forJob(appQuartz.getJobClassname(), appQuartz.getJobGroup())
                .build();

        //传递参数
        if(appQuartz.getInvokeParam()!=null && !"".equals(appQuartz.getInvokeParam())) {
            simpleTrigger.getJobDataMap().put("invokeParam",appQuartz.getInvokeParam());
        }
        try {
            scheduler.scheduleJob(jobDetail, simpleTrigger);
            return "success";
        } catch (SchedulerException e) {
            System.out.println("创建定时任务失败" + e);
            return e.getMessage();
        }
    }

    /**
     * 暂停job
     */
    public String pausejob(Integer[] quartzIds) throws Exception {
        AppQuartz appQuartz=null;
        if(quartzIds.length>0){
            for(Integer quartzId:quartzIds) {
                //这里要先查询出任务信息,暂停需要任务名字和组名
                jobPause(appQuartz.getJobClassname(), appQuartz.getJobGroup());
            }
            return "success";
        }else {
            return "fail pauseJob";
        }
    }

    public void jobPause(String jobClassName, String jobGroupName) throws Exception {
        scheduler.pauseJob(JobKey.jobKey(jobClassName, jobGroupName));
    }


    /**
     * 恢复job
     * @param quartzIds
     * @return
     */
    public String resumejob(Integer[] quartzIds) throws SchedulerException {
        AppQuartz appQuartz=null;
        if(quartzIds.length>0){
            for(Integer quartzId:quartzIds) {
                //这里要先查询出任务信息,暂停需要任务名字和组名
                jobResume(appQuartz.getJobClassname(), appQuartz.getJobGroup());
            }
            return "success";
        }else {
            return "fail pauseJob";
        }
    }
    public void jobResume(String jobClassName, String jobGroupName) throws SchedulerException {
        scheduler.pauseJob(JobKey.jobKey(jobClassName, jobGroupName));
    }


    /**
     * 删除job
     * @param quartzIds
     * @return
     * @throws Exception
     */
    public String deletjob(Integer[] quartzIds) throws Exception {
        AppQuartz appQuartz=null;
        if(quartzIds.length>0){
            for(Integer quartzId:quartzIds) {
                //这里要先查询出任务信息,暂停需要任务名字和组名
                jobDelete(appQuartz.getJobClassname(), appQuartz.getJobGroup());
            }
            return "success";
        }else {
            return "fail pauseJob";
        }
    }
    public void jobDelete(String jobClassName, String jobGroupName) throws Exception {
        scheduler.pauseTrigger(TriggerKey.triggerKey(jobClassName, jobGroupName));
        scheduler.unscheduleJob(TriggerKey.triggerKey(jobClassName, jobGroupName));
        scheduler.deleteJob(JobKey.jobKey(jobClassName, jobGroupName));
    }


    /**
     * 修改任务
     * @param appQuartz
     * @return
     */
    public String modifyJob(AppQuartz appQuartz) throws Exception {
        jobreschedule(appQuartz.getJobClassname(), appQuartz.getJobGroup(), appQuartz.getCronExpression());
        return "success";
    }
    public void jobreschedule(String jobClassName, String jobGroupName, String cronExpression) throws Exception {
            TriggerKey triggerKey = TriggerKey.triggerKey(jobClassName, jobGroupName);
            // 表达式调度构建器
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cronExpression);

            CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);

            // 按新的cronExpression表达式重新构建trigger
            trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build();

            // 按新的trigger重新设置job执行
            scheduler.rescheduleJob(triggerKey, trigger);

    }


    /**
     * 暂停所有任务
     * @return
     * @throws SchedulerException
     */
    public String pauseAllJob() throws SchedulerException {
        scheduler.pauseAll();
        return "success";
    }

    /**
     * 恢复所有任务
     * @return
     * @throws SchedulerException
     */
    public String resumeAllJob() throws SchedulerException {
        scheduler.resumeAll();
        return "success";
    }

    /**
     * 根据类名称,通过反射得到该类,然后创建一个BaseJob的实例。
     * 由于自己的Job类都实现了BaseJob,
     * 所以这里不需要我们手动去判断。这里涉及到了一些java多态调用的机制
     *
     * @param classname
     * @return
     * @throws Exception
     */
    public static BaseJob getClass(String classname) throws Exception {
        Class class1 = Class.forName(classname);
        return (BaseJob) class1.newInstance();
    }

    /**
     * 查询任务
     * 这里因为自己建了任务信息表,就直接查自己的表就可以啦
     * 不然的话要连表查询quartz自带的好几张表
     */
}

7.封装定时任务接口

package com.example.demo_quartz.controller;

import com.example.demo_quartz.pojo.AppQuartz;
import com.example.demo_quartz.service.QuartzService;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/quartz")
public class QuartzController {

    @Autowired
    private QuartzService quartzService;

    //测试
    @RequestMapping(value="/test",method=RequestMethod.GET)
    public String test() throws Exception {
        return "success";
    }

    //添加一个job
    @RequestMapping(value="/addJob",method=RequestMethod.POST)
    public String addjob(@RequestBody AppQuartz appQuartz) throws Exception {
        return quartzService.addJob(appQuartz);
    }

    //暂停job
    @RequestMapping(value="/pauseJob",method=RequestMethod.POST)
    public String pausejob(@RequestBody Integer[]quartzIds) {
        try {
            return quartzService.pausejob(quartzIds);
        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        }
    }

    //恢复job
    @RequestMapping(value="/resumeJob",method=RequestMethod.POST)
    public String resumejob(@RequestBody Integer[]quartzIds){
        try {
            return quartzService.resumejob(quartzIds);
        } catch (SchedulerException e) {
            e.printStackTrace();
            return e.getMessage();
        }
    }


    //删除job
    @RequestMapping(value="/deletJob",method=RequestMethod.POST)
    public String deletjob(@RequestBody Integer[]quartzIds){
        try {
            return quartzService.deletjob(quartzIds);
        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        }
    }

    //修改
    @RequestMapping(value="/updateJob",method= RequestMethod.POST)
    public String  modifyJob(@RequestBody AppQuartz appQuartz){
        try {
            return quartzService.modifyJob(appQuartz);
        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        }
    }

    //暂停所有
    @RequestMapping(value="/pauseAll",method=RequestMethod.GET)
    public String pauseAllJob(){
        try {
            return quartzService.pauseAllJob();
        } catch (SchedulerException e) {
            e.printStackTrace();
            return e.getMessage();
        }
    }

    //恢复所有
    @RequestMapping(value="/repauseAll",method=RequestMethod.GET)
    public String repauseAllJob() throws Exception {
        return quartzService.resumeAllJob();
    }
}


8.运行

D:\ruanJian\JDK1_8\bin\java -agentlib:jdwp=transport=dt_socket,address=127.0.0.1:56684,suspend=y,server=n -XX:TieredStopAtLevel=1 -noverify -Dspring.output.ansi.enabled=always -Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.port=56683 -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false -Djava.rmi.server.hostname=localhost -Dspring.liveBeansView.mbeanDomain -Dspring.application.admin.enabled=true -javaagent:D:\ruanJian\Idea\2017.3.4\lib\rt\debugger-agent.jar=C:\Users\Administrator\AppData\Local\Temp\capture1813.props -Dfile.encoding=UTF-8 -classpath D:\ruanJian\JDK1_8\jre\lib\charsets.jar;D:\ruanJian\JDK1_8\jre\lib\deploy.jar;D:\ruanJian\JDK1_8\jre\lib\ext\access-bridge-64.jar;D:\ruanJian\JDK1_8\jre\lib\ext\cldrdata.jar;D:\ruanJian\JDK1_8\jre\lib\ext\dnsns.jar;D:\ruanJian\JDK1_8\jre\lib\ext\jaccess.jar;D:\ruanJian\JDK1_8\jre\lib\ext\jfxrt.jar;D:\ruanJian\JDK1_8\jre\lib\ext\localedata.jar;D:\ruanJian\JDK1_8\jre\lib\ext\nashorn.jar;D:\ruanJian\JDK1_8\jre\lib\ext\sunec.jar;D:\ruanJian\JDK1_8\jre\lib\ext\sunjce_provider.jar;D:\ruanJian\JDK1_8\jre\lib\ext\sunmscapi.jar;D:\ruanJian\JDK1_8\jre\lib\ext\sunpkcs11.jar;D:\ruanJian\JDK1_8\jre\lib\ext\zipfs.jar;D:\ruanJian\JDK1_8\jre\lib\javaws.jar;D:\ruanJian\JDK1_8\jre\lib\jce.jar;D:\ruanJian\JDK1_8\jre\lib\jfr.jar;D:\ruanJian\JDK1_8\jre\lib\jfxswt.jar;D:\ruanJian\JDK1_8\jre\lib\jsse.jar;D:\ruanJian\JDK1_8\jre\lib\management-agent.jar;D:\ruanJian\JDK1_8\jre\lib\plugin.jar;D:\ruanJian\JDK1_8\jre\lib\resources.jar;D:\ruanJian\JDK1_8\jre\lib\rt.jar;E:\ideaWorkSpace\demo_quartz\target\classes;D:\ruanJian\mavenRepository\org\springframework\boot\spring-boot-starter-web\2.1.4.RELEASE\spring-boot-starter-web-2.1.4.RELEASE.jar;D:\ruanJian\mavenRepository\org\springframework\boot\spring-boot-starter\2.1.4.RELEASE\spring-boot-starter-2.1.4.RELEASE.jar;D:\ruanJian\mavenRepository\org\springframework\boot\spring-boot\2.1.4.RELEASE\spring-boot-2.1.4.RELEASE.jar;D:\ruanJian\mavenRepository\org\springframework\boot\spring-boot-autoconfigure\2.1.4.RELEASE\spring-boot-autoconfigure-2.1.4.RELEASE.jar;D:\ruanJian\mavenRepository\org\springframework\boot\spring-boot-starter-logging\2.1.4.RELEASE\spring-boot-starter-logging-2.1.4.RELEASE.jar;D:\ruanJian\mavenRepository\ch\qos\logback\logback-classic\1.2.3\logback-classic-1.2.3.jar;D:\ruanJian\mavenRepository\ch\qos\logback\logback-core\1.2.3\logback-core-1.2.3.jar;D:\ruanJian\mavenRepository\org\apache\logging\log4j\log4j-to-slf4j\2.11.2\log4j-to-slf4j-2.11.2.jar;D:\ruanJian\mavenRepository\org\apache\logging\log4j\log4j-api\2.11.2\log4j-api-2.11.2.jar;D:\ruanJian\mavenRepository\org\slf4j\jul-to-slf4j\1.7.26\jul-to-slf4j-1.7.26.jar;D:\ruanJian\mavenRepository\javax\annotation\javax.annotation-api\1.3.2\javax.annotation-api-1.3.2.jar;D:\ruanJian\mavenRepository\org\yaml\snakeyaml\1.23\snakeyaml-1.23.jar;D:\ruanJian\mavenRepository\org\springframework\boot\spring-boot-starter-json\2.1.4.RELEASE\spring-boot-starter-json-2.1.4.RELEASE.jar;D:\ruanJian\mavenRepository\com\fasterxml\jackson\core\jackson-databind\2.9.8\jackson-databind-2.9.8.jar;D:\ruanJian\mavenRepository\com\fasterxml\jackson\core\jackson-annotations\2.9.0\jackson-annotations-2.9.0.jar;D:\ruanJian\mavenRepository\com\fasterxml\jackson\core\jackson-core\2.9.8\jackson-core-2.9.8.jar;D:\ruanJian\mavenRepository\com\fasterxml\jackson\datatype\jackson-datatype-jdk8\2.9.8\jackson-datatype-jdk8-2.9.8.jar;D:\ruanJian\mavenRepository\com\fasterxml\jackson\datatype\jackson-datatype-jsr310\2.9.8\jackson-datatype-jsr310-2.9.8.jar;D:\ruanJian\mavenRepository\com\fasterxml\jackson\module\jackson-module-parameter-names\2.9.8\jackson-module-parameter-names-2.9.8.jar;D:\ruanJian\mavenRepository\org\springframework\boot\spring-boot-starter-tomcat\2.1.4.RELEASE\spring-boot-starter-tomcat-2.1.4.RELEASE.jar;D:\ruanJian\mavenRepository\org\apache\tomcat\embed\tomcat-embed-core\9.0.17\tomcat-embed-core-9.0.17.jar;D:\ruanJian\mavenRepository\org\apache\tomcat\embed\tomcat-embed-el\9.0.17\tomcat-embed-el-9.0.17.jar;D:\ruanJian\mavenRepository\org\apache\tomcat\embed\tomcat-embed-websocket\9.0.17\tomcat-embed-websocket-9.0.17.jar;D:\ruanJian\mavenRepository\org\hibernate\validator\hibernate-validator\6.0.16.Final\hibernate-validator-6.0.16.Final.jar;D:\ruanJian\mavenRepository\javax\validation\validation-api\2.0.1.Final\validation-api-2.0.1.Final.jar;D:\ruanJian\mavenRepository\org\jboss\logging\jboss-logging\3.3.2.Final\jboss-logging-3.3.2.Final.jar;D:\ruanJian\mavenRepository\com\fasterxml\classmate\1.4.0\classmate-1.4.0.jar;D:\ruanJian\mavenRepository\org\springframework\spring-web\5.1.6.RELEASE\spring-web-5.1.6.RELEASE.jar;D:\ruanJian\mavenRepository\org\springframework\spring-beans\5.1.6.RELEASE\spring-beans-5.1.6.RELEASE.jar;D:\ruanJian\mavenRepository\org\springframework\spring-webmvc\5.1.6.RELEASE\spring-webmvc-5.1.6.RELEASE.jar;D:\ruanJian\mavenRepository\org\springframework\spring-aop\5.1.6.RELEASE\spring-aop-5.1.6.RELEASE.jar;D:\ruanJian\mavenRepository\org\springframework\spring-context\5.1.6.RELEASE\spring-context-5.1.6.RELEASE.jar;D:\ruanJian\mavenRepository\org\springframework\spring-expression\5.1.6.RELEASE\spring-expression-5.1.6.RELEASE.jar;D:\ruanJian\mavenRepository\org\slf4j\slf4j-api\1.7.26\slf4j-api-1.7.26.jar;D:\ruanJian\mavenRepository\org\springframework\spring-core\5.1.6.RELEASE\spring-core-5.1.6.RELEASE.jar;D:\ruanJian\mavenRepository\org\springframework\spring-jcl\5.1.6.RELEASE\spring-jcl-5.1.6.RELEASE.jar;D:\ruanJian\mavenRepository\org\springframework\boot\spring-boot-starter-quartz\2.1.4.RELEASE\spring-boot-starter-quartz-2.1.4.RELEASE.jar;D:\ruanJian\mavenRepository\org\springframework\spring-context-support\5.1.6.RELEASE\spring-context-support-5.1.6.RELEASE.jar;D:\ruanJian\mavenRepository\org\springframework\spring-tx\5.1.6.RELEASE\spring-tx-5.1.6.RELEASE.jar;D:\ruanJian\mavenRepository\org\quartz-scheduler\quartz\2.3.1\quartz-2.3.1.jar;D:\ruanJian\mavenRepository\com\mchange\mchange-commons-java\0.2.15\mchange-commons-java-0.2.15.jar;D:\ruanJian\mavenRepository\com\zaxxer\HikariCP-java7\2.4.13\HikariCP-java7-2.4.13.jar;D:\ruanJian\mavenRepository\com\alibaba\druid\1.1.9\druid-1.1.9.jar;D:\ruanJian\mavenRepository\mysql\mysql-connector-java\8.0.15\mysql-connector-java-8.0.15.jar;D:\ruanJian\Idea\2017.3.4\lib\idea_rt.jar com.example.demo_quartz.DemoQuartzApplication
Connected to the target VM, address: '127.0.0.1:56684', transport: 'socket'

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.4.RELEASE)

2019-09-05 15:22:58.974  INFO 14548 --- [           main] c.e.demo_quartz.DemoQuartzApplication    : Starting DemoQuartzApplication on H1F0FQ9L16KP8PA with PID 14548 (E:\ideaWorkSpace\demo_quartz\target\classes started by Administrator in E:\ideaWorkSpace\demo_quartz)
2019-09-05 15:22:58.977  INFO 14548 --- [           main] c.e.demo_quartz.DemoQuartzApplication    : No active profile set, falling back to default profiles: default
2019-09-05 15:22:59.689  INFO 14548 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2019-09-05 15:22:59.705  INFO 14548 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2019-09-05 15:22:59.705  INFO 14548 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.17]
2019-09-05 15:22:59.787  INFO 14548 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2019-09-05 15:22:59.787  INFO 14548 --- [           main] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 770 ms
2019-09-05 15:22:59.816  INFO 14548 --- [           main] o.q.e.servlet.QuartzInitializerListener  : Quartz Initializer Servlet loaded, initializing Scheduler...
2019-09-05 15:22:59.854  INFO 14548 --- [           main] org.quartz.impl.StdSchedulerFactory      : Using default implementation for ThreadExecutor
2019-09-05 15:22:59.862  INFO 14548 --- [           main] org.quartz.core.SchedulerSignalerImpl    : Initialized Scheduler Signaller of type: class org.quartz.core.SchedulerSignalerImpl
2019-09-05 15:22:59.862  INFO 14548 --- [           main] org.quartz.core.QuartzScheduler          : Quartz Scheduler v.2.3.1 created.
2019-09-05 15:22:59.862  INFO 14548 --- [           main] org.quartz.impl.jdbcjobstore.JobStoreTX  : Using thread monitor-based data access locking (synchronization).
2019-09-05 15:22:59.863  INFO 14548 --- [           main] org.quartz.impl.jdbcjobstore.JobStoreTX  : JobStoreTX initialized.
2019-09-05 15:22:59.863  INFO 14548 --- [           main] org.quartz.core.QuartzScheduler          : Scheduler meta-data: Quartz Scheduler (v2.3.1) 'QuartzScheduler' with instanceId 'NON_CLUSTERED'
  Scheduler class: 'org.quartz.core.QuartzScheduler' - running locally.
  NOT STARTED.
  Currently in standby mode.
  Number of jobs executed: 0
  Using thread pool 'org.quartz.simpl.SimpleThreadPool' - with 5 threads.
  Using job-store 'org.quartz.impl.jdbcjobstore.JobStoreTX' - which supports persistence. and is not clustered.

2019-09-05 15:22:59.863  INFO 14548 --- [           main] org.quartz.impl.StdSchedulerFactory      : Quartz scheduler 'QuartzScheduler' initialized from default resource file in Quartz package: 'quartz.properties'
2019-09-05 15:22:59.863  INFO 14548 --- [           main] org.quartz.impl.StdSchedulerFactory      : Quartz scheduler version: 2.3.1
2019-09-05 15:22:59.907  INFO 14548 --- [           main] com.alibaba.druid.pool.DruidDataSource   : {dataSource-1} inited
2019-09-05 15:23:00.087  INFO 14548 --- [           main] org.quartz.impl.jdbcjobstore.JobStoreTX  : Freed 0 triggers from 'acquired' / 'blocked' state.
2019-09-05 15:23:00.124  INFO 14548 --- [           main] org.quartz.impl.jdbcjobstore.JobStoreTX  : Recovering 0 jobs that were in-progress at the time of the last shut-down.
2019-09-05 15:23:00.124  INFO 14548 --- [           main] org.quartz.impl.jdbcjobstore.JobStoreTX  : Recovery complete.
2019-09-05 15:23:00.125  INFO 14548 --- [           main] org.quartz.impl.jdbcjobstore.JobStoreTX  : Removed 0 'complete' triggers.
2019-09-05 15:23:00.132  INFO 14548 --- [           main] org.quartz.impl.jdbcjobstore.JobStoreTX  : Removed 0 stale fired job entries.
2019-09-05 15:23:00.133  INFO 14548 --- [           main] org.quartz.core.QuartzScheduler          : Scheduler QuartzScheduler_$_NON_CLUSTERED started.
2019-09-05 15:23:00.133  INFO 14548 --- [           main] o.q.e.servlet.QuartzInitializerListener  : Scheduler has been started...
2019-09-05 15:23:00.133  INFO 14548 --- [           main] o.q.e.servlet.QuartzInitializerListener  : Storing the Quartz Scheduler Factory in the servlet context at key: org.quartz.impl.StdSchedulerFactory.KEY
2019-09-05 15:23:00.152  INFO 14548 --- [           main] org.quartz.impl.StdSchedulerFactory      : Using default implementation for ThreadExecutor
2019-09-05 15:23:00.152  INFO 14548 --- [           main] org.quartz.core.SchedulerSignalerImpl    : Initialized Scheduler Signaller of type: class org.quartz.core.SchedulerSignalerImpl
2019-09-05 15:23:00.152  INFO 14548 --- [           main] org.quartz.core.QuartzScheduler          : Quartz Scheduler v.2.3.1 created.
2019-09-05 15:23:00.152  INFO 14548 --- [           main] org.quartz.impl.jdbcjobstore.JobStoreTX  : Using thread monitor-based data access locking (synchronization).
2019-09-05 15:23:00.152  INFO 14548 --- [           main] org.quartz.impl.jdbcjobstore.JobStoreTX  : JobStoreTX initialized.
2019-09-05 15:23:00.152  INFO 14548 --- [           main] org.quartz.core.QuartzScheduler          : Scheduler meta-data: Quartz Scheduler (v2.3.1) 'SchedulerFactory' with instanceId 'NON_CLUSTERED'
  Scheduler class: 'org.quartz.core.QuartzScheduler' - running locally.
  NOT STARTED.
  Currently in standby mode.
  Number of jobs executed: 0
  Using thread pool 'org.quartz.simpl.SimpleThreadPool' - with 5 threads.
  Using job-store 'org.quartz.impl.jdbcjobstore.JobStoreTX' - which supports persistence. and is not clustered.

2019-09-05 15:23:00.152  INFO 14548 --- [           main] org.quartz.impl.StdSchedulerFactory      : Quartz scheduler 'SchedulerFactory' initialized from an externally provided properties instance.
2019-09-05 15:23:00.152  INFO 14548 --- [           main] org.quartz.impl.StdSchedulerFactory      : Quartz scheduler version: 2.3.1
2019-09-05 15:23:00.153  INFO 14548 --- [           main] org.quartz.core.QuartzScheduler          : JobFactory set to: org.springframework.scheduling.quartz.AdaptableJobFactory@75483843
2019-09-05 15:23:00.272  INFO 14548 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2019-09-05 15:23:00.426  INFO 14548 --- [           main] o.s.s.quartz.SchedulerFactoryBean        : Starting Quartz Scheduler now
2019-09-05 15:23:00.429  INFO 14548 --- [           main] com.alibaba.druid.pool.DruidDataSource   : {dataSource-2} inited
2019-09-05 15:23:00.436  INFO 14548 --- [           main] org.quartz.impl.jdbcjobstore.JobStoreTX  : Freed 0 triggers from 'acquired' / 'blocked' state.
2019-09-05 15:23:00.438  INFO 14548 --- [           main] org.quartz.impl.jdbcjobstore.JobStoreTX  : Recovering 0 jobs that were in-progress at the time of the last shut-down.
2019-09-05 15:23:00.438  INFO 14548 --- [           main] org.quartz.impl.jdbcjobstore.JobStoreTX  : Recovery complete.
2019-09-05 15:23:00.439  INFO 14548 --- [           main] org.quartz.impl.jdbcjobstore.JobStoreTX  : Removed 0 'complete' triggers.
2019-09-05 15:23:00.439  INFO 14548 --- [           main] org.quartz.impl.jdbcjobstore.JobStoreTX  : Removed 0 stale fired job entries.
2019-09-05 15:23:00.440  INFO 14548 --- [           main] org.quartz.core.QuartzScheduler          : Scheduler SchedulerFactory_$_NON_CLUSTERED started.
2019-09-05 15:23:00.463  INFO 14548 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2019-09-05 15:23:00.465  INFO 14548 --- [           main] c.e.demo_quartz.DemoQuartzApplication    : Started DemoQuartzApplication in 1.786 seconds (JVM running for 2.346)

9.测试

暂停所有任务成功
springboot+quartz实现动态任务管理,携带参数. 使用druid连接mysql数据库持久化.完整代码,有问题留言一起探讨_第2张图片

10.代码

正在学习如何上传到GitHub

11.补充

package com.example.quartz.tool;

import org.quartz.DateBuilder;
import org.springframework.stereotype.Component;

/**
* 日期工具类
*/
@Component
public class DateUnit {

    public DateBuilder.IntervalUnit verification(Integer timeType) {
        switch (timeType) {
            case 1:
                DateBuilder.IntervalUnit year = DateBuilder.IntervalUnit.YEAR;
                return year;
            case 2:
                DateBuilder.IntervalUnit month = DateBuilder.IntervalUnit.MONTH;
                return month;
            case 3:
                DateBuilder.IntervalUnit day = DateBuilder.IntervalUnit.DAY;
                return day;
            case 4:
                DateBuilder.IntervalUnit hour = DateBuilder.IntervalUnit.HOUR;
                return hour;
            case 5:
                DateBuilder.IntervalUnit second = DateBuilder.IntervalUnit.MINUTE;
                return second;
            case 6:
                DateBuilder.IntervalUnit week = DateBuilder.IntervalUnit.WEEK;
                return week;
            default:
                return DateBuilder.IntervalUnit.SECOND;
        }
    }

}

你可能感兴趣的:(java,java,springboot,quartz,druid,动态任务)