SpringBoot結合Quartz實現數據庫存儲

一、先創建一個SpringBoot項目

還有一個截屏忘瞭截屏,就是選擇保存路徑選擇一下就點Finish就可以瞭。 

更改application.properties為application.yml

application.yml文件如下

server:
  port: 8080
 
 
 
#數據庫連接池druid配置
 
spring:
  datasource:
    #1.JDBC
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/quartz?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&useSSL=false
    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: 127.0.0.1
 
 
mybatis:
  mapper-locations: classpath*:mapper/*.xml
 
  type-aliases-package: com.zking.quartz02.model
 
 

二、導入依賴 

1.導入Quartz依賴

<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>

2.用於我用的是Druid數據庫連接池,所以我需要更換成Druid連接池,先引入Druid依賴。

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

三、 導入DruidConnectionProvider.java(Druid連接池的Quartz擴展類)

package com.zking.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擴展類]
 */
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配置(在項目中添加quartz.properties文件(這樣就不會加載自帶的properties文件) )

#
#============================================================================
# Configure Main Scheduler Properties \u8C03\u5EA6\u5668\u5C5E\u6027
#============================================================================
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
#============================================================================
#\u5B58\u50A8\u65B9\u5F0F\u4F7F\u7528JobStoreTX\uFF0C\u4E5F\u5C31\u662F\u6570\u636E\u5E93
org.quartz.jobStore.class: org.quartz.impl.jdbcjobstore.JobStoreTX
org.quartz.jobStore.driverDelegateClass:org.quartz.impl.jdbcjobstore.StdJDBCDelegate
#\u4F7F\u7528\u81EA\u5DF1\u7684\u914D\u7F6E\u6587\u4EF6
org.quartz.jobStore.useProperties:true
#\u6570\u636E\u5E93\u4E2Dquartz\u8868\u7684\u8868\u540D\u524D\u7F00
org.quartz.jobStore.tablePrefix:qrtz_
org.quartz.jobStore.dataSource:qzDS
#\u662F\u5426\u4F7F\u7528\u96C6\u7FA4\uFF08\u5982\u679C\u9879\u76EE\u53EA\u90E8\u7F72\u5230 \u4E00\u53F0\u670D\u52A1\u5668\uFF0C\u5C31\u4E0D\u7528\u4E86\uFF09
org.quartz.jobStore.isClustered = true
#============================================================================
# Configure Datasources
#============================================================================
#\u914D\u7F6E\u6570\u636E\u5E93\u6E90
org.quartz.dataSource.qzDS.connectionProvider.class: com.zking.quartz02.utils.DruidConnectionProvider
org.quartz.dataSource.qzDS.driver: com.mysql.cj.jdbc.Driver
#修改為自己的數據庫名稱、用戶名和密碼
org.quartz.dataSource.qzDS.URL: jdbc:mysql://localhost:3306/quartz?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&useSSL=false
org.quartz.dataSource.qzDS.user: root
org.quartz.dataSource.qzDS.password: 123
org.quartz.dataSource.qzDS.maxConnection: 10

在數據庫中創建quartz相關的表
   進入quartz的官網http://www.quartz-scheduler.org/,點擊Downloads,
   下載後在目錄\docs\dbTables下有常用數據庫創建quartz表的腳本,例如:“tables_mysql.sql”

五、自定義MyJobFactory,解決spring不能在quartz中註入bean的問題

package com.zking.quartz02.quartz;
 
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;
 
//解決spring不能在quartz中註入bean的問題
@Component
public class MyJobFactory extends AdaptableJobFactory {
 
    @Autowired
    private AutowireCapableBeanFactory autowireCapableBeanFactory;
 
    @Override
    protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception {
        Object jobInstance = super.createJobInstance(bundle);
        autowireCapableBeanFactory.autowireBean(jobInstance);
        return jobInstance;
    }
}

六、創建調度器schedule

package com.zking.quartz02.quartz;
 
//quartz配置類將調度器交給spring管理
 
import org.quartz.Scheduler;
import org.quartz.SchedulerFactory;
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.annotation.Scheduled;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
 
import java.io.IOException;
import java.util.Properties;
 
@Configuration
public class QuartzConfiguration {
 
    @Autowired
    private  MyJobFactory myJobFactory;
 
    @Bean
    public Scheduler scheduler(){
        return this.getSchedulerFactoryBean().getScheduler();
    }
 
    //讀取自定義配置文件,獲取調度器工廠
    @Bean
    public SchedulerFactoryBean getSchedulerFactoryBean(){
        //1.創建SchedulerFactoryBean sc=new SchedulerFactoryBean
        SchedulerFactoryBean sc=new SchedulerFactoryBean();
        //2.加載自定義的quartz.properties
        sc.setQuartzProperties(this.getProperties());
        //3.設置自定義的MyJobFactory
        sc.setJobFactory(myJobFactory);
 
        return sc;
    }
 
    //讀取配置文件
    @Bean
    public Properties getProperties(){
 
        try {
            PropertiesFactoryBean propertiesFactoryBean =
                    new PropertiesFactoryBean();
 
            //設置自定義配置文件位置
            propertiesFactoryBean.setLocation(new ClassPathResource("/quartz.properties"));
            //讀取配置文件
            propertiesFactoryBean.afterPropertiesSet();
 
            return  propertiesFactoryBean.getObject();
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
 
 
    }
 
 
}

七、 創建自定義任務

 首先我們需要自己創建一張表t_schedule_trigger,用來存放trigger的信息,然後從數據庫讀取這些信息來隨時更新定時任務
   註意:job_name存放的任務類的全路徑,在quartz中通過jobName和jobGroup來確定trigger的唯一性,所以這兩列為聯合唯一索引 

t_schedule_trigger和t_schedule_trigger_param表生成的sql代碼如下(去執行一下sql語句即可)

 
-- 註意: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)
);

   註1:t_schedule_trigger的子表t_schedule_trigger_param還可以用來傳遞額外添加到任務中的參數

   註2:實現org.quartz.Job或org.springframework.scheduling.quartz.QuartzJobBean創建任務,可通過JobExecutionContext傳參

八、 更新quartz中的任務

首先我們將t_schedule_trigger和t_schedule_trigger_param通過generatorConfig.xml自動生成實體類,XXmapper.java,XXmapper.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:\\installpath\\apache-maven-3.5.4\\jar\\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="com.mysql.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/quartz?useUnicode=true&amp;characterEncoding=UTF-8" userId="root" password="123"/>
 
        <!-- 類型轉換 -->
        <javaTypeResolver>
            <!-- 是否使用bigDecimal, false可自動轉化以下類型(Long, Integer, Short, etc.) -->
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>
 
        <!-- 01 指定javaBean生成的位置 -->
        <!-- targetPackage:指定生成的model生成所在的包名 -->
        <!-- targetProject:指定在該項目下所在的路徑  -->
        <javaModelGenerator targetPackage="com.zking.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="mapper"
                         targetProject="src/main/resources">
            <!-- 是否允許子包,即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.zking.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>
 
        <!-- 配置表信息 -->
        <!-- schema即為數據庫名 -->
        <!-- tableName為對應的數據庫表 -->
        <!-- domainObjectName是要生成的實體類 -->
        <!-- enable*ByExample是否生成 example類 -->
        <!--<table schema="" tableName="t_book" domainObjectName="Book"-->
               <!--enableCountByExample="false" enableDeleteByExample="false"-->
               <!--enableSelectByExample="false" enableUpdateByExample="false">-->
            <!--&lt;!&ndash; 忽略列,不生成bean 字段 &ndash;&gt;-->
            <!--&lt;!&ndash; <ignoreColumn column="FRED" /> &ndash;&gt;-->
            <!--&lt;!&ndash; 指定列的java數據類型 &ndash;&gt;-->
            <!--&lt;!&ndash; <columnOverride column="LONG_VARCHAR_FIELD" jdbcType="VARCHAR" /> &ndash;&gt;-->
        <!--</table>-->
 
        <table schema="" tableName="t_schedule_trigger_param" domainObjectName="ScheduleTriggerParam"
               enableCountByExample="false" enableDeleteByExample="false"
               enableSelectByExample="false" enableUpdateByExample="false">
            <!-- 忽略列,不生成bean 字段 -->
            <!-- <ignoreColumn column="FRED" /> -->
            <!-- 指定列的java數據類型 -->
            <!-- <columnOverride column="LONG_VARCHAR_FIELD" jdbcType="VARCHAR" /> -->
        </table>
 
        <table schema="" tableName="t_schedule_trigger" domainObjectName="ScheduleTrigger"
               enableCountByExample="false" enableDeleteByExample="false"
               enableSelectByExample="false" enableUpdateByExample="false">
            <!-- 忽略列,不生成bean 字段 -->
            <!-- <ignoreColumn column="FRED" /> -->
            <!-- 指定列的java數據類型 -->
            <!-- <columnOverride column="LONG_VARCHAR_FIELD" jdbcType="VARCHAR" /> -->
        </table>
 
    </context>
</generatorConfiguration>

記得修改數據庫jdbc驅動jar包的位置為自己數據庫jdbc驅動jar包的位置,jdbc連接數據庫名、用戶名和密碼改為自己的。

註意:targetPackage改成自己的包名。

自動生成操作

命令:mybatis-generator:generate -e

註意:實體類上加一個@Data,XXmapper.java上加一個@Repository自己需要寫一個查詢全部的方法。

寫一個IScheduleService接口,用來定時刷新任務,更新調度器中的任務

package com.zking.quartz02.service;
 
public interface IScheduleService {
 
    //定時刷新任務,更新調度器中的任務
    public void refresh();
}

實現IScheduleService接口

package com.zking.quartz02.service.impl;
 
import com.zking.quartz02.mapper.ScheduleTriggerMapper;
import com.zking.quartz02.mapper.ScheduleTriggerParamMapper;
import com.zking.quartz02.model.ScheduleTrigger;
import com.zking.quartz02.model.ScheduleTriggerParam;
import com.zking.quartz02.service.IScheduleService;
import org.quartz.*;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
 
import javax.annotation.Resource;
import java.util.List;
 
@Service
public class ScheduleServiceImpl implements IScheduleService {
 
    @Resource
    private ScheduleTriggerMapper scheduleTriggerMapper;
 
    @Resource
    private ScheduleTriggerParamMapper scheduleTriggerParamMapper;
 
    @Resource
    private Scheduler scheduler;
 
    @Scheduled(cron = "*/10 * * * * ?")
    @Override
    public void refresh() {
 
        try {
            //1.查詢數據庫中所有的任務
            List<ScheduleTrigger> scheduleTriggers =
                    scheduleTriggerMapper.listScheduleTrigger();
 
            //2.遍歷所有任務
            for (ScheduleTrigger scheduleTrigger : scheduleTriggers) {
                Integer id = scheduleTrigger.getId();
                String cron = scheduleTrigger.getCron();
                String status = scheduleTrigger.getStatus();
                String jobName = scheduleTrigger.getJobName();
                String jobGroup = scheduleTrigger.getJobGroup();
 
                //設置triggerKey
                TriggerKey triggerKey = TriggerKey.triggerKey(jobName, jobGroup);
 
                //通過triggerKey獲取調度器中的觸發器
                CronTrigger cronTrigger = (CronTrigger)scheduler.getTrigger(triggerKey);
 
                if(null==cronTrigger){//如果為空,表示調度器中沒有該任務,不存在就添加任務
                    if("0".equals(status)){//如果該任務狀態為0,表示該任務不用添加,此次循環結束
                        continue;
                    }
 
                    //創建觸發器
                    CronTrigger cronTrigger1 = TriggerBuilder.newTrigger()
                            .withIdentity(jobName, jobGroup)
                            .withSchedule(CronScheduleBuilder.cronSchedule(cron))
                            .build();
 
                    //創建工作詳情實例
                    JobDetail jobDetail = JobBuilder.newJob((Class<? extends Job>) Class.forName(jobName))
                            .withIdentity(jobName, jobGroup)
                            .build();
 
                    JobDataMap jobDataMap = jobDetail.getJobDataMap();
 
 
                    //查詢該任務中所有的參數
                    List<ScheduleTriggerParam> scheduleTriggerParams = scheduleTriggerParamMapper.listScheduleTriggerParamById(id);
 
 
                    //遍歷所有參數,將參數設置到jobDataMap中
                    for (ScheduleTriggerParam scheduleTriggerParam : scheduleTriggerParams) {
                        jobDataMap.put(scheduleTriggerParam.getName(),scheduleTriggerParam.getValue());
                    }
 
 
                    //添加任務,將觸發器和工作詳情實例添加到調度器中
                    scheduler.scheduleJob(jobDetail,cronTrigger1);
 
 
                }else{//如果不為空,表示調度器中存在該任務
                    if("0".equals(status)){//如果任務狀態改為禁用,移除該任務
                        JobKey jobKey = JobKey.jobKey(jobName, jobGroup);
                        scheduler.deleteJob(jobKey);//移除任務
                    }
 
 
 
                    //如果調度器中的觸發器的表達式和數據庫中的表達式不一致
 
                    //獲取調度器中觸發器的表達式
                    String cronExpression = cronTrigger.getCronExpression();
                    if(!cronExpression.equals(cron)){//不一致
                        //重新創建新的觸發器
                        CronTrigger cronTrigger2 = TriggerBuilder.newTrigger()
                                .withIdentity(jobName, jobGroup)
                                .withSchedule(CronScheduleBuilder.cronSchedule(cron))
                                .build();
 
                        //更新調度器中的觸發器
                        scheduler.rescheduleJob(triggerKey,cronTrigger2);
                    }
 
 
 
 
 
                }
            }
 
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
 
    }
}

1) service層實現類使用@Scheduled註解聲明一個方法用於定時刷新數據庫中的調度任務;
 2) 使用@Resource註解註入Scheduler,在第5點中已裝配到Spring上下文;

 3) 在啟動類上加入@MapperScan(指定要變成實現類的接口所在的包路徑,比如我的就是com.zking.quartz02.mapper),然後包下面的所有接口在編譯之後都會生成相應的實現類;
 4) 在啟動類上加入@EnableScheduling啟動Spring自帶定時器任務;

小結:

   要搞清楚一個問題:從數據庫讀取任務信息動態生成定時任務,和把quartz持久化到數據庫是沒有關系的。
   前者是我們自己定義的業務表,而後者是quartz使用自己的表來存儲信息。持久化到數據庫後,
   就算服務器重啟或是多個quartz節點也沒關系,因為他們共享數據庫中的任務信息。

到此這篇關於SpringBoot結合Quartz實現數據庫存儲的文章就介紹到這瞭,更多相關SpringBoot Quartz數據庫存儲內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: