SpringBoot+Quartz+数据库存储

目录
1、Spring整合Quartz
2、读取数据库来开启定时任务(案例)

Spring整合Quartz

a、quartz调度框架是有内置表的
进入quartz的官网 link,点击Downloads,
下载后在目录\docs\dbTables下有常用数据库创建quartz表的脚本,例如:“tables_mysql.sql”
table_mysql.sql
table_mysql_innodb.sql
上述两者所有的数据库引擎不一样SpringBoot+Quartz+数据库存储_第1张图片
比如我的是mysql数据库,它里面有11张表,这些表是我们后面操作Quartz需要的
SpringBoot+Quartz+数据库存储_第2张图片

b、导入pom依赖

<dependency>
	<groupId>org.quartz-scheduler</groupId>
	<artifactId>quartz-jobs</artifactId>
	<version>2.2.1</version>
   </dependency>
   <dependency>
   	<groupId>org.springframework.boot</groupId>
   	<artifactId>spring-boot-starter-quartz</artifactId>
   </dependency>
   <!--quartz需要使用C3P0连接池将数据持久化到数据库-->
   <!--Quartz各版本数据库连接池技术更新情况-->
   <!--Quartz 2.0 以前 DBCP-->
   <!--Quartz 2.0 以后 C3P0(包含2.0-->
   <dependency>
   	<groupId>com.mchange</groupId>
	<artifactId>c3p0</artifactId>
	<version>0.9.5.2</version>
   </dependency>

   更换成Druid连接池

   A、 引入依赖

   <dependency>
	<groupId>com.alibaba</groupId>
	<artifactId>druid-spring-boot-starter</artifactId>
	<version>1.1.10</version>
   </dependency>

   B、 导入DruidConnectionProvider.java

C、修改quartz.properties配置

#配置数据库源
org.quartz.dataSource.qzDS.connectionProvider.class:
com.javaxl.项目名.util.DruidConnectionProvider

c、在项目中添加quartz.properties文件(这样就不会加载自带的properties文件)
此文件的内容主要分为:scheduler,ThreadPool,JobStore,plugin,Datasources等部分,
覆盖properties文件的目的是覆盖默认的数据源,更换为druid的数据配置

d、自定义MyJobFactory,解决spring不能在quartz中注入bean的问题
e、创建调度器schedule,交给spring进行管理
f、创建自定义任务
g、更新quartz中的任务
h、自定义任务表与quartz内置表的区分

要搞清楚一个问题:从数据库读取任务信息动态生成定时任务,和把quartz持久化到数据库是没有关系的。前者是我们自己定义的业务表,而后者是quartz使用自己的表来存储信息。持久化到数据库后,就算服务器重启或是多个quartz节点也没关系,因为他们共享数据库中的任务信息。

自定义的业务表

-- 注意:job_name存放的任务类的全路径,在quartz中通过jobName和jobGroup来确定trigger的唯一性,所以这两列为联合唯一索引
create table t_schedule_trigger
(
  id int primary key auto_increment,                                -- ID
  cron varchar(200) not null,                                       -- 时间表达式
  status char(1) not null,                                          -- 使用状态 0:禁用   1:启用
  job_name varchar(200) not null,                                   -- 任务名称
  job_group varchar(200) not null,                                  -- 任务分组  
  unique index(job_name,job_group)
);

-- 额外添加到任务中的参数
create table t_schedule_trigger_param
(
  param_id int primary key auto_increment,                                -- ID
  name varchar(200) not null,                                             -- 参数名
  value varchar(512),                                                     -- 参数值
 
  schedule_trigger_id int not null,                                       -- 外键:引用t_schedule_trigger(id)
  foreign key(schedule_trigger_id) references t_schedule_trigger(id)
);

Quartz默认的连接池是c3p0,如果你的连接池不同需要直接替换它的配置文件,比如我用的连接池是druid,就需要自己改配置(如果就用c3p0就不需要改)

Druid连接池Quartz的工具类

DruidConnectionProvider

package com.cgl.quartz02.util;

import com.alibaba.druid.pool.DruidDataSource;
import org.quartz.SchedulerException;
import org.quartz.utils.ConnectionProvider;

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

/*
#============================================================================
# JDBC
#============================================================================
org.quartz.jobStore.driverDelegateClass:org.quartz.impl.jdbcjobstore.StdJDBCDelegate
org.quartz.jobStore.useProperties:false
org.quartz.jobStore.dataSource:qzDS
#org.quartz.dataSource.qzDS.connectionProvider.class:org.quartz..PoolingConnectionProvider
org.quartz.dataSource.qzDS.connectionProvider.class:com.zking.q03.quartz.DruidConnectionProvider
org.quartz.dataSource.qzDS.driver:com.mysql.jdbc.Driver
org.quartz.dataSource.qzDS.URL:jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=UTF-8
org.quartz.dataSource.qzDS.user:root
org.quartz.dataSource.qzDS.password:root
org.quartz.dataSource.qzDS.maxConnections:30
org.quartz.dataSource.qzDS.validationQuery: select 0
*/

/**
 * [Druid连接池的Quartz扩展类]
 *
 * @ProjectName: []
 * @Author: [xuguang]
 * @CreateDate: [2015/11/10 17:58]
 * @Update: [说明本次修改内容] BY[xuguang][2015/11/10]
 * @Version: [v1.0]
 */
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 datasource;

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

    public void shutdown() throws SQLException {
        datasource.close();
    }
    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!");
        }

        datasource = new DruidDataSource();
        try{
            datasource.setDriverClassName(this.driver);
        } catch (Exception e) {
            try {
                throw new SchedulerException("Problem setting driver class name on datasource: " + e.getMessage(), e);
            } catch (SchedulerException e1) {
            }
        }

        datasource.setUrl(this.URL);
        datasource.setUsername(this.user);
        datasource.setPassword(this.password);
        datasource.setMaxActive(this.maxConnection);
        datasource.setMinIdle(1);
        datasource.setMaxWait(0);
        datasource.setMaxPoolPreparedStatementPerConnectionSize(this.DEFAULT_DB_MAX_CACHED_STATEMENTS_PER_CONNECTION);

        if (this.validationQuery != null) {
            datasource.setValidationQuery(this.validationQuery);
            if(!this.validateOnCheckout)
                datasource.setTestOnReturn(true);
            else
                datasource.setTestOnBorrow(true);
            datasource.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 datasource;
    }

    public void setDatasource(DruidDataSource datasource) {
        this.datasource = datasource;
    }
}

quartz.properties

#
#============================================================================
# Configure Main Scheduler Properties 调度器属性
#============================================================================
org.quartz.scheduler.instanceName: DefaultQuartzScheduler
org.quartz.scheduler.instanceId = AUTO
org.quartz.scheduler.rmi.export: false
org.quartz.scheduler.rmi.proxy: false
org.quartz.scheduler.wrapJobExecutionInUserTransaction: false
org.quartz.threadPool.class: org.quartz.simpl.SimpleThreadPool
org.quartz.threadPool.threadCount= 10
org.quartz.threadPool.threadPriority: 5
org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread: true
org.quartz.jobStore.misfireThreshold: 60000
#============================================================================
# Configure JobStore
#============================================================================
#存储方式使用JobStoreTX,也就是数据库
org.quartz.jobStore.class: org.quartz.impl.jdbcjobstore.JobStoreTX
org.quartz.jobStore.driverDelegateClass:org.quartz.impl.jdbcjobstore.StdJDBCDelegate
#使用自己的配置文件
org.quartz.jobStore.useProperties:true
#数据库中quartz表的表名前缀
org.quartz.jobStore.tablePrefix:qrtz_
org.quartz.jobStore.dataSource:qzDS
#是否使用集群(如果项目只部署到 一台服务器,就不用了)
org.quartz.jobStore.isClustered = true
#============================================================================
# Configure Datasources
#============================================================================
#配置数据库源(org.quartz.dataSource.qzDS.maxConnections: c3p0配置的是有s的,druid数据源没有s)
org.quartz.dataSource.qzDS.connectionProvider.class:com.cgl.quartz02.util.DruidConnectionProvider
org.quartz.dataSource.qzDS.driver: com.mysql.jdbc.Driver
org.quartz.dataSource.qzDS.URL: jdbc:mysql://localhost:3306/pages?useUnicode=true&characterEncoding=utf8
org.quartz.dataSource.qzDS.user: root
org.quartz.dataSource.qzDS.password: 123
org.quartz.dataSource.qzDS.maxConnection: 10

然后在后面把这个文件配会丢入我们的配置文件中

需要配置我们的JobFactory,因为我们在项目开发中是需要在Job中操作数据库的,那么当然需要把它交给spring管理,但是quartz本身是不支持的,所以我们需要修改它的底层代码,让我们的Job类能被spring所管理

MyJobFactory

package com.cgl.quartz02.util;

import lombok.extern.slf4j.Slf4j;
import org.quartz.spi.TriggerFiredBundle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.scheduling.quartz.AdaptableJobFactory;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class MyJobFactory extends AdaptableJobFactory {

    //这个对象Spring会帮我们自动注入进来
    @Autowired
    private AutowireCapableBeanFactory autowireCapableBeanFactory;

    //重写创建Job任务的实例方法
    @Override
    protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception {
        Object jobInstance = super.createJobInstance(bundle);
        //通过以下方式,解决Job任务无法使用Spring中的Bean问题
        autowireCapableBeanFactory.autowireBean(jobInstance);
        return super.createJobInstance(bundle);
    }
}

然后把刚刚写的配置全部丢进我们的配置类中

QuartzConfiguration

package com.cgl.quartz02.config;

import com.cgl.quartz02.util.MyJobFactory;
import org.quartz.Scheduler;
import org.springframework.beans.factory.annotation.Autowired;
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 QuartzConfiguration {

    @Autowired
    private MyJobFactory myJobFactory;

    //创建调度器工厂
    @Bean
        public SchedulerFactoryBean schedulerFactoryBean(){
            //1.创建SchedulerFactoryBean
            //2.加载自定义的quartz.properties配置文件
            //3.设置MyJobFactory

            SchedulerFactoryBean factoryBean=new SchedulerFactoryBean();
            try {
                factoryBean.setQuartzProperties(quartzProperties());
                factoryBean.setJobFactory(myJobFactory);
                return factoryBean;
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
    }

    @Bean
    public Properties quartzProperties() throws IOException {
        PropertiesFactoryBean propertiesFactoryBean=new PropertiesFactoryBean();
        propertiesFactoryBean.setLocation(new ClassPathResource("/quartz.properties"));
        propertiesFactoryBean.afterPropertiesSet();
        return propertiesFactoryBean.getObject();
    }

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

案例中需要观察表数据变化的表

-- 自定义的业务表
SELECT * FROM t_schedule_trigger;
SELECT * FROM t_schedule_trigger_param;

-- quartz调度框架自带的表
SELECT * FROM qrtz_scheduler_state;
SELECT * FROM qrtz_cron_triggers;
SELECT * FROM qrtz_simple_triggers
SELECT * FROM qrtz_triggers;
SELECT * FROM qrtz_job_details;

SpringBoot+Quartz+数据库存储_第3张图片
SpringBoot+Quartz+数据库存储_第4张图片
pom依赖

 <dependency>
            <groupId>org.quartz-scheduler</groupId>
            <artifactId>quartz-jobs</artifactId>
            <version>2.2.1</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.10</version>
        </dependency>


<resources>
        <!--解决mybatis-generator-maven-plugin运行时没有将XxxMapper.xml文件放入target文件夹的问题-->
        <resource>
            <directory>src/main/java</directory>
            <includes>
                <include>**/*.xml
            
        
        
        
            src/main/resources
            
                *.properties
                *.xml
                *.yml
            
        
        


                org.mybatis.generator
                mybatis-generator-maven-plugin
                1.3.2
                
                    
                    
                        mysql
                        mysql-connector-java
                        ${mysql.version}
                    
                
                
                    true
                
            

application.yml

server:
  servlet:
    context-path: /
  port: 80
spring:
  datasource:
    #1.JDBC
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/pages?useUnicode=true&characterEncoding=utf8
    username: root
    password: 123
    druid:
      #2.\u8FDE\u63A5\u6C60\u914D\u7F6E
      #\u521D\u59CB\u5316\u8FDE\u63A5\u6C60\u7684\u8FDE\u63A5\u6570\u91CF \u5927\u5C0F\uFF0C\u6700\u5C0F\uFF0C\u6700\u5927
      initial-size: 5
      min-idle: 5
      max-active: 20
      #\u914D\u7F6E\u83B7\u53D6\u8FDE\u63A5\u7B49\u5F85\u8D85\u65F6\u7684\u65F6\u95F4
      max-wait: 60000
      #\u914D\u7F6E\u95F4\u9694\u591A\u4E45\u624D\u8FDB\u884C\u4E00\u6B21\u68C0\u6D4B\uFF0C\u68C0\u6D4B\u9700\u8981\u5173\u95ED\u7684\u7A7A\u95F2\u8FDE\u63A5\uFF0C\u5355\u4F4D\u662F\u6BEB\u79D2
      time-between-eviction-runs-millis: 60000
      # \u914D\u7F6E\u4E00\u4E2A\u8FDE\u63A5\u5728\u6C60\u4E2D\u6700\u5C0F\u751F\u5B58\u7684\u65F6\u95F4\uFF0C\u5355\u4F4D\u662F\u6BEB\u79D2
      min-evictable-idle-time-millis: 30000
      validation-query: SELECT 1 FROM DUAL
      test-while-idle: true
      test-on-borrow: true
      test-on-return: false
      # \u662F\u5426\u7F13\u5B58preparedStatement\uFF0C\u4E5F\u5C31\u662FPSCache  \u5B98\u65B9\u5EFA\u8BAEMySQL\u4E0B\u5EFA\u8BAE\u5173\u95ED   \u4E2A\u4EBA\u5EFA\u8BAE\u5982\u679C\u60F3\u7528SQL\u9632\u706B\u5899 \u5EFA\u8BAE\u6253\u5F00
      pool-prepared-statements: true
      max-pool-prepared-statement-per-connection-size: 20
      # \u914D\u7F6E\u76D1\u63A7\u7EDF\u8BA1\u62E6\u622A\u7684filters\uFF0C\u53BB\u6389\u540E\u76D1\u63A7\u754C\u9762sql\u65E0\u6CD5\u7EDF\u8BA1\uFF0C'wall'\u7528\u4E8E\u9632\u706B\u5899
      filter:
        stat:
          merge-sql: true
          slow-sql-millis: 5000
      #3.\u57FA\u7840\u76D1\u63A7\u914D\u7F6E
      web-stat-filter:
        enabled: true
        url-pattern: /*
        #\u8BBE\u7F6E\u4E0D\u7EDF\u8BA1\u54EA\u4E9BURL
        exclusions: "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*"
        session-stat-enable: true
        session-stat-max-count: 100
      stat-view-servlet:
        enabled: true
        url-pattern: /druid/*
        reset-enable: true
        #\u8BBE\u7F6E\u76D1\u63A7\u9875\u9762\u7684\u767B\u5F55\u540D\u548C\u5BC6\u7801
        login-username: admin
        login-password: admin
        allow: 127.0.0.1
        #deny: 192.168.1.100

#pagehelper\u5206\u9875\u63D2\u4EF6\u914D\u7F6E
pagehelper:
  helperDialect: mysql
  reasonable: true
  supportMethodsArguments: true
  params: count=countSql

#\u663E\u793A\u65E5\u5FD7
logging:
  level:
    com.cgl.quartz02.mapper: debug

Quartz02Application.java

package com.cgl.quartz02;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@MapperScan("com.cgl.quartz02.mapper")
@EnableTransactionManagement
@EnableScheduling
@SpringBootApplication
public class Quartz02Application {

    public static void main(String[] args) {
        SpringApplication.run(Quartz02Application.class, args);
    }

}

generatorConfig.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd" >
<generatorConfiguration>
    <!-- 引入配置文件 -->
    <properties resource="jdbc.properties"/>

    <!--指定数据库jdbc驱动jar包的位置-->
    <classPathEntry location="E:\Mavenhuanjin\maven_repository\mysql\mysql-connector-java\\5.1.44\\mysql-connector-java-5.1.44.jar"/>
    <!-- 一个数据库一个context -->
    <context id="infoGuardian">
        <!-- 注释 -->
        <commentGenerator>
            <property name="suppressAllComments" value="true"/><!-- 是否取消注释 -->
            <property name="suppressDate" value="true"/> <!-- 是否生成注释代时间戳 -->
        </commentGenerator>

        <!-- jdbc连接 -->
        <jdbcConnection driverClass="${jdbc.driver}"
                        connectionURL="${jdbc.url}" userId="${jdbc.username}" password="${jdbc.password}"/>

        <!-- 类型转换 -->
        <javaTypeResolver>
            <!-- 是否使用bigDecimal, false可自动转化以下类型(Long, Integer, Short, etc.-->
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>

        <!-- 01 指定javaBean生成的位置 -->
        <!-- targetPackage:指定生成的model生成所在的包名 -->
        <!-- targetProject:指定在该项目下所在的路径  -->
        <javaModelGenerator targetPackage="com.cgl.quartz02.model"
                            targetProject="src/main/java">
            <!-- 是否允许子包,即targetPackage.schemaName.tableName -->
            <property name="enableSubPackages" value="false"/>
            <!-- 是否对model添加构造函数 -->
            <property name="constructorBased" value="true"/>
            <!-- 是否针对string类型的字段在set的时候进行trim调用 -->
            <property name="trimStrings" value="false"/>
            <!-- 建立的Model对象是否 不可改变  即生成的Model对象不会有 setter方法,只有构造方法 -->
            <property name="immutable" value="false"/>
        </javaModelGenerator>

        <!-- 02 指定sql映射文件生成的位置 -->
        <sqlMapGenerator targetPackage="com.cgl.quartz02.mapper"
                         targetProject="src/main/java">
            <!-- 是否允许子包,即targetPackage.schemaName.tableName -->
            <property name="enableSubPackages" value="false"/>
        </sqlMapGenerator>

        <!-- 03 生成XxxMapper接口 -->
        <!-- type="ANNOTATEDMAPPER",生成Java Model 和基于注解的Mapper对象 -->
        <!-- type="MIXEDMAPPER",生成基于注解的Java Model 和相应的Mapper对象 -->
        <!-- type="XMLMAPPER",生成SQLMap XML文件和独立的Mapper接口 -->
        <javaClientGenerator targetPackage="com.cgl.quartz02.mapper"
                             targetProject="src/main/java" type="XMLMAPPER">
            <!-- 是否在当前路径下新加一层schema,false路径com.oop.eksp.user.model, true:com.oop.eksp.user.model.[schemaName] -->
            <property name="enableSubPackages" value="false"/>
        </javaClientGenerator>

        <!-- 配置表信息 -->
        <table schema="" tableName="t_schedule_trigger" domainObjectName="ScheduleTrigger"
               enableCountByExample="false" enableDeleteByExample="false"
               enableSelectByExample="false" enableUpdateByExample="false">
            <property name="useActualColumnNames" value="true" />
        </table>
        <table schema="" tableName="t_schedule_trigger_param" domainObjectName="ScheduleTriggerParam"
               enableCountByExample="false" enableDeleteByExample="false"
               enableSelectByExample="false" enableUpdateByExample="false">
            <property name="useActualColumnNames" value="true" />
        </table>

    </context>
</generatorConfiguration>

jdbc.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/pages?useUnicode=true&characterEncoding=UTF-8
jdbc.username=root
jdbc.password=123
jdbc.initialSize=10
jdbc.maxTotal=100
jdbc.maxIdle=50
jdbc.minIdle=10
jdbc.maxWaitMillis=-1

ScheduleTriggerMapper.java

package com.cgl.quartz02.mapper;

import com.cgl.quartz02.model.ScheduleTrigger;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface ScheduleTriggerMapper {
    int deleteByPrimaryKey(Integer id);

    int insert(ScheduleTrigger record);

    int insertSelective(ScheduleTrigger record);

    ScheduleTrigger selectByPrimaryKey(Integer id);

    int updateByPrimaryKeySelective(ScheduleTrigger record);

    int updateByPrimaryKey(ScheduleTrigger record);

    /**
     * 查询触发器中包含的所有任务
     * @return
     */
    List<ScheduleTrigger> queryScheduleTriggerLst();
}

ScheduleTriggerParamMapper.java

/**
     * 查询出当前任务类对应所需的参数
     * @param triggerId
     * @return
     */
    List<ScheduleTriggerParam> queryScheduleParamLst(Integer triggerId);

ScheduleTriggerMapper.xml

<select id="queryScheduleTriggerLst" resultType="com.javaxl.quartz02.model.ScheduleTrigger">
    select <include refid="Base_Column_List"/>
    from t_schedule_trigger
  </select>

ScheduleTriggerParamMapper.xml

 <select id="queryScheduleParamLst" resultType="com.javaxl.quartz02.model.ScheduleTriggerParam">
    select <include refid="Base_Column_List"/>
    from t_schedule_trigger_param where schedule_trigger_id=#{triggerId}
  </select>

ScheduleTriggerParamServiceImpl.java

@Service
public class ScheduleTriggerParamServiceImpl implements ScheduleTriggerParamService {

    @Autowired
    private ScheduleTriggerParamMapper scheduleTriggerParamMapper;

    @Override
    public List<ScheduleTriggerParam> queryScheduleParamLst(Integer triggerId) {
        return scheduleTriggerParamMapper.queryScheduleParamLst(triggerId);
    }
}

spring自带定时任务作业类ScheduleTriggerServiceImpl.java

package com.cgl.quartz02.service.impl;

import com.cgl.quartz02.mapper.ScheduleTriggerMapper;
import com.cgl.quartz02.mapper.ScheduleTriggerParamMapper;
import com.cgl.quartz02.model.ScheduleTrigger;
import com.cgl.quartz02.model.ScheduleTriggerParam;
import com.cgl.quartz02.service.ScheduleTriggerService;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ScheduleTriggerServiceImpl implements ScheduleTriggerService {

    @Autowired
    private ScheduleTriggerMapper scheduleTriggerMapper;

    @Autowired
    private ScheduleTriggerParamMapper scheduleTriggerParamMapper;

    @Autowired
    private Scheduler scheduler;

    @Override
    public int deleteByPrimaryKey(Integer id) {
        return scheduleTriggerMapper.deleteByPrimaryKey(id);
    }

    @Override
    public int insert(ScheduleTrigger record) {
        return scheduleTriggerMapper.insert(record);
    }

    @Override
    public int insertSelective(ScheduleTrigger record) {
        return scheduleTriggerMapper.insertSelective(record);
    }

    @Override
    public ScheduleTrigger selectByPrimaryKey(Integer id) {
        return scheduleTriggerMapper.selectByPrimaryKey(id);
    }

    @Override
    public int updateByPrimaryKeySelective(ScheduleTrigger record) {
        return scheduleTriggerMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public int updateByPrimaryKey(ScheduleTrigger record) {
        return scheduleTriggerMapper.updateByPrimaryKey(record);
    }

    @Override
    public List<ScheduleTrigger> queryScheduleTriggerLst() {
        return scheduleTriggerMapper.queryScheduleTriggerLst();
    }


    @Scheduled(cron = "0/10 * * * * ?")
    public void refreshScheduler(){
        try {
            List<ScheduleTrigger> scheduleTriggers =
                    scheduleTriggerMapper.queryScheduleTriggerLst();
            if(null!=scheduleTriggers){
                for (ScheduleTrigger scheduleTrigger : scheduleTriggers) {
                    String cron = scheduleTrigger.getCron();  //表达式
                    String jobName = scheduleTrigger.getJob_name(); //任务名称
                    String jobGroup = scheduleTrigger.getJob_group(); //任务分组
                    String status = scheduleTrigger.getStatus();  //任务状态

                    //JobName+JobGroup=Primary Key
                    //根据jobName和jobGroup生成TriggerKey
                    TriggerKey triggerKey =
                            TriggerKey.triggerKey(jobName, jobGroup);
                    //根据TriggerKey到Scheduler调度器中获取触发器是从quartz自带表中读取数据
                    CronTrigger cronTrigger = (CronTrigger)
                            scheduler.getTrigger(triggerKey);

                    if(null==cronTrigger){
                        if(status.equals("0"))
                            continue;
                        System.out.println("创建调度器");
                        //创建任务详情
                        JobDetail jobDetail=
                                JobBuilder.newJob((Class<? extends Job>) Class.forName(jobName))
                                .withIdentity(jobName,jobGroup)
                                .build();

                        //往Job任务中传递参数
                        JobDataMap jobDataMap = jobDetail.getJobDataMap();
                        List<ScheduleTriggerParam> params =
                                scheduleTriggerParamMapper.queryScheduleParamLst(scheduleTrigger.getId());
                        for (ScheduleTriggerParam param : params) {
                            jobDataMap.put(param.getName(),param.getValue());
                        }

                        //创建表达式调度器,将自定义的任务表数据同步到quartz内置读取中
                        CronScheduleBuilder cronSchedule =
                                CronScheduleBuilder.cronSchedule(cron);

                        //创建Trigger
                        cronTrigger=TriggerBuilder.newTrigger()
                                    .withIdentity(jobName,jobGroup)
                                    .withSchedule(cronSchedule)
                                    .build();

                        //将jobDetail和Trigger注入到scheduler调度器中
                        scheduler.scheduleJob(jobDetail,cronTrigger);
                    }else{
                        System.err.println("Quartz 调度任务中已存在该任务");
                        if(status.equals("0")){
                            JobKey jobKey = JobKey.jobKey(jobName, jobGroup);
                            scheduler.deleteJob(jobKey);
                            continue;
                        }
                        //调度器中的表达式,获取quartz内置表的数据表达式
                        String cronExpression =
                                cronTrigger.getCronExpression();

                        if(!cron.equals(cronExpression)){
                            //创建表达式调度器
                            CronScheduleBuilder cronSchedule =
                                    CronScheduleBuilder.cronSchedule(cron);

                            //重构
                            cronTrigger=cronTrigger.getTriggerBuilder()
                                    .withIdentity(triggerKey)
                                    .withSchedule(cronSchedule)
                                    .build();

                            //刷新调度器
                            scheduler.rescheduleJob(triggerKey,cronTrigger);
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}

读取数据库来开启定时任务(案例)

那么我们还需要自己创建两张表,通过这两张表和Quartz的内置表来管理动态的定时任务,表里面的数据我们测试用的数据

t_schedule_trigger,管理具体的任务,
id:标识列
cron:表达式
status(0关闭,1开启)是否开启
job_name:job的name
job_group:job的group
SpringBoot+Quartz+数据库存储_第5张图片
t_schedule_trigger——param,管理传递的参数
SpringBoot+Quartz+数据库存储_第6张图片
MyJob(更改定时任务状态)

当禁用该触发器时,那么程序只会执行spring自带的定时任务,每10s执行一次查询,所以打印语句如上。

package com.cgl.quartz02.quartz;

import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
@Slf4j
public class MyJob implements Job {

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        System.out.println("MyJob是一个空的任务计划,时间:"+new Date().toLocaleString());
    }
}

MyJob1(定时任务中携带参数)

程序执行spring自带的定时任务,每10s执行一次查询,查询t_schedule_trigger表,调度器表中有两个调度器,都是每5s执行一次,其中一个调度器是需要携带参数的,携带的参数在t_schedule_trigger_param表中,所以一开始调度器启动的时候需要查询t_schedule_trigger_param表数据,最终打印语句如上。

package com.cgl.quartz02.quartz;

import com.cgl.quartz02.service.ScheduleTriggerParamService;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @author caoguangli
 * @site www.xiaomage.com
 * @company
 * @create  2019-12-02 12:40
 */
@Component
@Slf4j
public class MyJob1 implements Job {

    @Autowired
    private ScheduleTriggerParamService scheduleTriggerParamService;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        JobDetail jobDetail =
                jobExecutionContext.getJobDetail();
        JobDataMap jobDataMap = jobDetail.getJobDataMap();
        System.out.println(new Date().toLocaleString()+"-->携带参数个数:"+jobDataMap.size());
    }
}

MyJob2(更改定时任务规则)

程序执行spring自带的定时任务,每10s执行一次查询,查询t_schedule_trigger表,将任务3的表达式由0/3 * * * * ?改成0/20 * * * * ?,最终结果如上

package com.cgl.quartz02.quartz;

import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @author caoguangli
 * @site www.xiaomage.com
 * @company
 * @create  2019-12-02 12:43
 */
@Component
@Slf4j
public class MyJob2 implements Job {
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        JobDetail jobDetail =
                jobExecutionContext.getJobDetail();
        JobDataMap jobDataMap = jobDetail.getJobDataMap();
        System.out.println(new Date().toLocaleString()+"-->MyJob2参数传递name="+jobDataMap.get("name")+",score="+
                jobDataMap.get("score"));
    }
}

控制器

ScheduleTriggerController

package com.cgl.quartz02.controller;

import com.cgl.quartz02.model.ScheduleTrigger;
import com.cgl.quartz02.service.ScheduleTriggerService;
import com.cgl.quartz02.util.PageBean;
import com.cgl.quartz02.util.PageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author caoguangli
 * @site www.xiaomage.com
 * @company
 * @create  2019-12-02 13:34
 */
@Controller
@RequestMapping("quartz")
public class ScheduleTriggerController {

    @Autowired
    private ScheduleTriggerService scheduleTriggerService;


    @RequestMapping("/listPager")
    public ModelAndView list(ScheduleTrigger scheduleTrigger,
                             HttpServletRequest request) {
        PageBean pageBean = new PageBean();
        pageBean.setRequest(request);
        ModelAndView modelAndView = new ModelAndView();
        List<ScheduleTrigger> quartzs = scheduleTriggerService.queryScheduleTriggerLst();
        modelAndView.addObject("quartzs",quartzs);
        pageBean.setTotal(pageBean.getTotal()+"");
        modelAndView.addObject("pageCode", PageUtil.createPageCode
                (pageBean)/*.replaceAll("<","<").replaceAll(">:",">")*/);
        modelAndView.setViewName("list");
        return modelAndView;
    }


    @RequestMapping("/toEdit")
    public ModelAndView toEdit(ScheduleTrigger scheduleTrigger){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("edit");
        modelAndView.addObject("statusArr",new String[]{"0","1"});
        if(!(scheduleTrigger.getId() == null || "".equals(scheduleTrigger.getId
                ()))) {
            ScheduleTrigger t = scheduleTriggerService.selectByPrimaryKey
                    (scheduleTrigger.getId());
            modelAndView.addObject("quartz", t);
        }
        else{
            modelAndView.addObject("quartz", new ScheduleTrigger());
        }

        return modelAndView;
    }

    @RequestMapping("/add")
    public String add(ScheduleTrigger scheduleTrigger){
       int n =  scheduleTriggerService.insert(scheduleTrigger);
        scheduleTriggerService.refreshScheduler();
        return "redirect:/quartz/listPager";
    }


    @RequestMapping("/edit")
    public String edit(ScheduleTrigger scheduleTrigger){
        scheduleTriggerService.updateByPrimaryKey(scheduleTrigger);
        scheduleTriggerService.refreshScheduler();
        return "redirect:/quartz/listPager";
    }
    @RequestMapping("/refresh")
    public String refresh(ScheduleTrigger scheduleTrigger){
        scheduleTriggerService.refreshScheduler();
        return "redirect:/quartz/listPager";
    }



}

templates模板

list.html

<!DOCTYPE html>
<html lang="en">
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>书籍列表</title>
    <script type="text/javascript" th:src="@{/static/js/xxx.js}"></script>
    <link rel="stylesheet" th:href="@{/static/js/bootstrap3/css/bootstrap.min.css}">
    <link rel="stylesheet" th:href="@{/static/js/bootstrap3/css/bootstrap-theme.min.css}">
    <script type="text/javascript" th:src="@{/static/js/bootstrap3/js/jquery-1.11.2.min.js}"></script>
    <script type="text/javascript" th:src="@{/static/js/bootstrap3/js/bootstrap.min.js}"></script>
</head>
<body>
<a th:href="@{/quartz/toEdit}">新增</a>
<a th:href="@{/quartz/refresh}">刷新</a>
<table border="1px" width="600px">
    <thead>
    <tr>
        <td>ID</td>
        <td>cron语法</td>
        <td>可否用</td>
        <td>调用任务</td>
        <td></td>
        <td>操作</td>
    </tr>
    </thead>
    <tbody>
    <tr th:each="quartz : ${quartzs}">
        <td th:text="${quartz.id}"></td>
        <td th:text="${quartz.cron}"></td>
        <td th:text="${quartz.status}"></td>
        <td th:text="${quartz.job_name}"></td>
        <td th:text="${quartz.job_group}"></td>
        <td>
            <a th:href="@{'/quartz/toEdit?id='+${quartz.id}}">修改</a>
        </td>
    </tr>
    </tbody>
</table>


<nav>
    <ul class="pagination pagination-sm" th:utext="${pageCode}">
    </ul>
</nav>
</body>
</html>

edit.html

<!DOCTYPE html>
<html lang="en">
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>定时任务编辑界面</title>

    <script type="text/javascript">
        function preShow() {

        }
    </script>
</head>
<body>

<form th:action="${quartz.id} != -1  ? '/quartz/edit' : '/quartz/add'" method="post" >
    <input type="hidden" name="id" th:value="${quartz.id}" />
    cron语法: <input type="text" name="cron" th:value="${quartz.cron}" /></br>
    调用任务的路径: <input type="text" name="job_name" th:value="${quartz.job_name}" /></br>
    调用任务分组: <input type="text" name="job_group" th:value="${quartz.job_group}" /></br>
    是否可用
    <input type="radio" name="status"
           th:each ="s:${statusArr}"
           th:value="${s}"
           th:text ="${s}== 0 ? '不可用' : '可用' "
           th:attr ="checked=${s == quartz.status}">

    <input type="submit" value="提交"/>
</form>

</body>
</html>

最终效果
SpringBoot+Quartz+数据库存储_第7张图片
编辑界面
SpringBoot+Quartz+数据库存储_第8张图片

中途报了一个BUG,一直说我找不到模板,我一直以为我模板配置有问题,最后发现是连接池配置有问题…
在这里插入图片描述

在pom里面加上资源文件路径配置

<resource>
		<directory>src/main/resources</directory>
	</resource>

你可能感兴趣的:(SpringBoot+Quartz+数据库存储)