SpringBoot+Quartz+数据库存储

Spring 整合 Quartz

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

进入Quartz的官网:http://www.quartz-scheduler.org/,
点击Downloads,下载下来是一个完整的文件夹,我们需要进入 docs –> dbTables,在里面找到需要的数据库创建quartz表的脚本,然后把sql文件导入数据库,例如:“tables_mysql.sql”
在这里插入图片描述
table_mysql.sql
在这里插入图片描述
创建项目:
在这里插入图片描述
导入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>

重点:
Quartz2.0以前的数据库连接池是DBCP
Quartz2.0(包放2.0)以后的数据库连接池是C3P0
但是SpringBoot我们使用Druid,这就意味着我们要更换数据库源
两种解决方案:
第一种:把application.properties里面的Druid配置改成C3P0的配置
第二种:把Quartz默认的数据库连接池更换成Druid

这里我们采用第二种解决方案,因为Druid使用起来很方便,还可以看到后台的性能问题。
更换成Druid连接池

1、 引入依赖

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

2、 针对quartz.properties进行重写
在这里插入图片描述
重写quartz.properties文件

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

# Default Properties file for use by StdSchedulerFactory
# to create a Quartz Scheduler Instance, if a different
# properties file is not explicitly specified.
#

org.quartz.scheduler.instanceName: DefaultQuartzScheduler
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

org.quartz.jobStore.class: org.quartz.simpl.RAMJobStore


3、导入 DruidConnectionProvider.java

这是Queraz要用到的数据源

DruidConnectionProvider.java

package com.tanzhixian.quartz02.utils;

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.utils.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;
    }
}

4、自定义 MyJobFactory,解决 spring 不能在 quartz 中注入bean的问题

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

在MyJobFactory里重写创建Job任务的实例方法

MyJobFactory.java

package com.tanzhixian.quartz02.utils;

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);
    }
}

5、创建调度器 schedule,交给spring进行管理

把刚刚写的配置全部丢进配置类中

QuartzConfiguration.java

package com.tanzhixian.quartz02.config;

import com.tanzhixian.quartz02.utils.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();
    }
}

6、创建自定义任务

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

			t_schedule_trigger,管理具体的任务,
			id:标识列
			cron:表达式
			status(0关闭,1开启)是否开启
			job_name:job的name
			job_group:job的group
			t_schedule_trigger_param,管理传递的参数

t_schedule_trigger
在这里插入图片描述
t_schedule_trigger_param
在这里插入图片描述
用 mybatis 逆向生成这两张表的实体类和mapper:

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="D:\\initPath\\mvn_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.tanzhixian.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.tanzhixian.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.tanzhixian.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>

配置pom依赖


		<properties>
	        <java.version>1.8</java.version>
	        <mysql.version>5.1.44</mysql.version>
	    </properties>

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

			<plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.2</version>
                <dependencies>
                    <!--使用Mybatis-generator插件不能使用太高版本的mysql驱动 -->
                    <dependency>
                        <groupId>mysql</groupId>
                        <artifactId>mysql-connector-java</artifactId>
                        <version>${mysql.version}</version>
                    </dependency>
                </dependencies>
                <configuration>
                    <overwrite>true</overwrite>
                </configuration>
            </plugin>

application.yml

server:
  port: 8080
  servlet:
    context-path: /
spring:
  datasource:
    #1.JDBC
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/mysql?useUnicode=true&characterEncoding=utf8
    username: root
    password: 123
    druid:
      #2.连接池配置
      #初始化连接池的连接数量 大小,最小,最大
      initial-size: 5
      min-idle: 5
      max-active: 20
      #配置获取连接等待超时的时间
      max-wait: 60000
      #配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
      time-between-eviction-runs-millis: 60000
      # 配置一个连接在池中最小生存的时间,单位是毫秒
      min-evictable-idle-time-millis: 30000
      validation-query: SELECT 1 FROM DUAL
      test-while-idle: true
      test-on-borrow: true
      test-on-return: false
      # 是否缓存preparedStatement,也就是PSCache  官方建议MySQL下建议关闭   个人建议如果想用SQL防火墙 建议打开
      pool-prepared-statements: true
      max-pool-prepared-statement-per-connection-size: 20
      # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
      filter:
        stat:
          merge-sql: true
          slow-sql-millis: 5000
      #3.基础监控配置
      web-stat-filter:
        enabled: true
        url-pattern: /*
        #设置不统计哪些URL
        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
        #设置监控页面的登录名和密码
        login-username: admin
        login-password: admin
        allow: 192.168.65.128
        #deny: 192.168.1.100

#显示日志
logging:
  level:
    com.tanzhixian.quartz02.mapper: debug

ScheduleTriggerMapper.java

package com.tanzhixian.quartz02.mapper;

import com.tanzhixian.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();
}

ScheduleTriggerMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.tanzhixian.quartz02.mapper.ScheduleTriggerMapper" >
  <resultMap id="BaseResultMap" type="com.tanzhixian.quartz02.model.ScheduleTrigger" >
    <constructor >
      <idArg column="id" jdbcType="INTEGER" javaType="java.lang.Integer" />
      <arg column="cron" jdbcType="VARCHAR" javaType="java.lang.String" />
      <arg column="status" jdbcType="CHAR" javaType="java.lang.String" />
      <arg column="job_name" jdbcType="VARCHAR" javaType="java.lang.String" />
      <arg column="job_group" jdbcType="VARCHAR" javaType="java.lang.String" />
    </constructor>
  </resultMap>
  <sql id="Base_Column_List" >
    id, cron, status, job_name, job_group
  </sql>
  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
    select 
    <include refid="Base_Column_List" />
    from t_schedule_trigger
    where id = #{id,jdbcType=INTEGER}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
    delete from t_schedule_trigger
    where id = #{id,jdbcType=INTEGER}
  </delete>
  <insert id="insert" parameterType="com.tanzhixian.quartz02.model.ScheduleTrigger" >
    insert into t_schedule_trigger (id, cron, status, 
      job_name, job_group)
    values (#{id,jdbcType=INTEGER}, #{cron,jdbcType=VARCHAR}, #{status,jdbcType=CHAR}, 
      #{job_name,jdbcType=VARCHAR}, #{job_group,jdbcType=VARCHAR})
  </insert>
  <insert id="insertSelective" parameterType="com.tanzhixian.quartz02.model.ScheduleTrigger" >
    insert into t_schedule_trigger
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="id != null" >
        id,
      </if>
      <if test="cron != null" >
        cron,
      </if>
      <if test="status != null" >
        status,
      </if>
      <if test="job_name != null" >
        job_name,
      </if>
      <if test="job_group != null" >
        job_group,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="id != null" >
        #{id,jdbcType=INTEGER},
      </if>
      <if test="cron != null" >
        #{cron,jdbcType=VARCHAR},
      </if>
      <if test="status != null" >
        #{status,jdbcType=CHAR},
      </if>
      <if test="job_name != null" >
        #{job_name,jdbcType=VARCHAR},
      </if>
      <if test="job_group != null" >
        #{job_group,jdbcType=VARCHAR},
      </if>
    </trim>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="com.tanzhixian.quartz02.model.ScheduleTrigger" >
    update t_schedule_trigger
    <set >
      <if test="cron != null" >
        cron = #{cron,jdbcType=VARCHAR},
      </if>
      <if test="status != null" >
        status = #{status,jdbcType=CHAR},
      </if>
      <if test="job_name != null" >
        job_name = #{job_name,jdbcType=VARCHAR},
      </if>
      <if test="job_group != null" >
        job_group = #{job_group,jdbcType=VARCHAR},
      </if>
    </set>
    where id = #{id,jdbcType=INTEGER}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.tanzhixian.quartz02.model.ScheduleTrigger" >
    update t_schedule_trigger
    set cron = #{cron,jdbcType=VARCHAR},
      status = #{status,jdbcType=CHAR},
      job_name = #{job_name,jdbcType=VARCHAR},
      job_group = #{job_group,jdbcType=VARCHAR}
    where id = #{id,jdbcType=INTEGER}
  </update>

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

ScheduleTriggerParamMapper.java

package com.tanzhixian.quartz02.mapper;

import com.tanzhixian.quartz02.model.ScheduleTriggerParam;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface ScheduleTriggerParamMapper {
    int deleteByPrimaryKey(Integer param_id);

    int insert(ScheduleTriggerParam record);

    int insertSelective(ScheduleTriggerParam record);

    ScheduleTriggerParam selectByPrimaryKey(Integer param_id);

    int updateByPrimaryKeySelective(ScheduleTriggerParam record);

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

ScheduleTriggerParamMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.tanzhixian.quartz02.mapper.ScheduleTriggerParamMapper" >
  <resultMap id="BaseResultMap" type="com.tanzhixian.quartz02.model.ScheduleTriggerParam" >
    <constructor >
      <idArg column="param_id" jdbcType="INTEGER" javaType="java.lang.Integer" />
      <arg column="name" jdbcType="VARCHAR" javaType="java.lang.String" />
      <arg column="value" jdbcType="VARCHAR" javaType="java.lang.String" />
      <arg column="schedule_trigger_id" jdbcType="INTEGER" javaType="java.lang.Integer" />
    </constructor>
  </resultMap>
  <sql id="Base_Column_List" >
    param_id, name, value, schedule_trigger_id
  </sql>
  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
    select 
    <include refid="Base_Column_List" />
    from t_schedule_trigger_param
    where param_id = #{param_id,jdbcType=INTEGER}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
    delete from t_schedule_trigger_param
    where param_id = #{param_id,jdbcType=INTEGER}
  </delete>
  <insert id="insert" parameterType="com.tanzhixian.quartz02.model.ScheduleTriggerParam" >
    insert into t_schedule_trigger_param (param_id, name, value, 
      schedule_trigger_id)
    values (#{param_id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}, #{value,jdbcType=VARCHAR}, 
      #{schedule_trigger_id,jdbcType=INTEGER})
  </insert>
  <insert id="insertSelective" parameterType="com.tanzhixian.quartz02.model.ScheduleTriggerParam" >
    insert into t_schedule_trigger_param
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="param_id != null" >
        param_id,
      </if>
      <if test="name != null" >
        name,
      </if>
      <if test="value != null" >
        value,
      </if>
      <if test="schedule_trigger_id != null" >
        schedule_trigger_id,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="param_id != null" >
        #{param_id,jdbcType=INTEGER},
      </if>
      <if test="name != null" >
        #{name,jdbcType=VARCHAR},
      </if>
      <if test="value != null" >
        #{value,jdbcType=VARCHAR},
      </if>
      <if test="schedule_trigger_id != null" >
        #{schedule_trigger_id,jdbcType=INTEGER},
      </if>
    </trim>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="com.tanzhixian.quartz02.model.ScheduleTriggerParam" >
    update t_schedule_trigger_param
    <set >
      <if test="name != null" >
        name = #{name,jdbcType=VARCHAR},
      </if>
      <if test="value != null" >
        value = #{value,jdbcType=VARCHAR},
      </if>
      <if test="schedule_trigger_id != null" >
        schedule_trigger_id = #{schedule_trigger_id,jdbcType=INTEGER},
      </if>
    </set>
    where param_id = #{param_id,jdbcType=INTEGER}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.tanzhixian.quartz02.model.ScheduleTriggerParam" >
    update t_schedule_trigger_param
    set name = #{name,jdbcType=VARCHAR},
      value = #{value,jdbcType=VARCHAR},
      schedule_trigger_id = #{schedule_trigger_id,jdbcType=INTEGER}
    where param_id = #{param_id,jdbcType=INTEGER}
  </update>

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

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

ScheduleTriggerServiceImpl

package com.tanzhixian.quartz02.service.impl;

import com.tanzhixian.quartz02.mapper.ScheduleTriggerMapper;
import com.tanzhixian.quartz02.mapper.ScheduleTriggerParamMapper;
import com.tanzhixian.quartz02.model.ScheduleTrigger;
import com.tanzhixian.quartz02.model.ScheduleTriggerParam;
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 {

    @Autowired
    private ScheduleTriggerMapper scheduleTriggerMapper;

    @Autowired
    private ScheduleTriggerParamMapper scheduleTriggerParamMapper;

    @Autowired
    private Scheduler scheduler;

    @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调度器中获取触发器
                    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());
                        }

                        //创建表达式调度器
                        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;
                        }
                        //调度器中的表达式
                        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();
        }
    }
}

读取数据库中表达式启动定时任务

MyJob.java

package com.tanzhixian.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());
    }
}

在这里插入图片描述
qrtz_triggers
在这里插入图片描述

更改定时任务状态

将其禁用
在这里插入图片描述
在这里插入图片描述

定时任务中携带参数

MyJob1.java

package com.tanzhixian.quartz02.quartz;

import com.tanzhixian.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大贤
 * @create  2019-12-03 18:59
 */
@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.err.println(new Date().toLocaleString()+"-->携带参数个数:"+jobDataMap.size());
    }
}

在这里插入图片描述

更改定时任务规则

MyJob2

package com.tanzhixian.quartz02.quartz;

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

import java.util.Date;

/**
 * @author大贤
 * @create  2019-12-03 19:03
 */
@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"));
    }
}

在这里插入图片描述
更改
在这里插入图片描述

在这里插入图片描述

界面展示:

package com.tanzhixian.quartz02.controller;

import com.tanzhixian.quartz02.model.ScheduleTrigger;
import com.tanzhixian.quartz02.service.ScheduleTriggerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;
	
	@Controller
	@RequestMapping("/quartz")
	public class QuartzController {
	
	    @Autowired
	    private ScheduleTriggerService scheduleTriggerService;
	
	    @RequestMapping("/list")
	    public ModelAndView getAll(){
	        ModelAndView mv = new ModelAndView();
	        List<ScheduleTrigger> list = scheduleTriggerService.queryScheduleTriggerList();
	        mv.addObject("quartzList",list);
	        mv.setViewName("index");
	        return mv;
	    }
	
	    @RequestMapping("/edit")
	    public String editStatus(ScheduleTrigger scheduleTrigger){
	        int n = scheduleTriggerService.updateByPrimaryKeySelective(scheduleTrigger);
	        return "redirect:/quartz/list";
	    }
	
	    @RequestMapping("/proSave/{id}")
	    public ModelAndView proSave(@PathVariable(value = "id") Integer id){
	        ModelAndView mv=new ModelAndView();
	        ScheduleTrigger scheduleTrigger = scheduleTriggerService.selectByPrimaryKey(id);
	        mv.addObject("schedule",scheduleTrigger);
	        mv.setViewName("edit");
	        return mv;
	    }
	
	}

list.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Quartz 定时任务管理 页面展示 </title>
</head>
<body>
<h1 style="text-align: center">定时任务管理</h1>
<table style="text-align: center" align="center" border="1px" width="50%">
    <tr>
        <td>任务id</td>
        <td>任务表达式</td>
        <td>任务状态</td>
        <td>job工作类</td>
        <td>job分组</td>
        <td>操作</td>
    </tr>
    <tr th:each="q : ${quartzList}">
        <td th:text="${q.id}"></td>
        <td th:text="${q.cron}"></td>
        <td th:text="${q.status}"></td>
        <td th:text="${q.job_name}"></td>
        <td th:text="${q.job_group}"></td>
        <td th:switch ="${q.status} == 0">
            <a th:case="true" th:href="@{/quartz/edit(id=${q.id},status=1)}">启动</a>
            <a th:case="false" th:href="@{/quartz/edit(id=${q.id},status=0)}">停止</a>
            <a th:href="@{'/quartz/proSave/'+${q.id}}">编辑</a>
        </td>
    </tr>
</table>
</body>
</html>

editt.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Quartz 编辑界面 </title>
</head>
<body>
<h1>编辑定时任务</h1>
<form th:action="@{/quartz/edit}" method="post">
    <input type="hidden" name="id" th:value="${schedule.id}" />
    任务表达式: <input width="300px" type="text" name="cron" th:value="${schedule.cron}" /></br>
    job工作类: <input width="300px" type="text" name="job_name" th:value="${schedule.job_name}" /></br>
    job分组:<input width="300px" type="text" name="job_group" th:value="${schedule.job_group}" /></br>
    <input type="submit" value="提交"/>
</form>
</body>
</html>

在这里插入图片描述

错误
在这里插入图片描述
在pom文件中加入就可以了

<resource>
                <directory>src/main/resources</directory>
            </resource>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值