天天看點

springboot內建quartz

springboot內建quartz完成定時任務

      • springboot整合Quartz
      • 案例

springboot整合Quartz

項目目錄

springboot內建quartz

1、quartz排程架構是有内置表的,首先需要進入Quartz官網,下載下傳使用所需要的内置表sql

官網:http://www.quartz-scheduler.org/

自動生成表達式:http://cron.qqe2.com/

下載下傳下來是一個完整的檔案夾,我們需要進入docs–>dbTables,然後在裡面找你需要的資料類型的sql,然後把sql檔案導入你的資料庫

我的是mysql資料庫,它裡面有11張表,引入之個即可

springboot內建quartz

2. 建立springboot項目,導入相關pom

pom

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.1.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.li</groupId>
    <artifactId>quartz02</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>quartz02</name>
    <description>Demo project for Spring Boot</description>

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

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-quartz</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.1</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql.version}</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

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

    </dependencies>


    <build>
        <resources>
<!--            -->
            <resource>
                <directory>src/main/resources</directory>
            </resource>
            <!--解決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>

        <plugins>
            <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>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>


           

3、Quartz預設的連接配接池是c3p0,如果連接配接池不同需要替換它的配置檔案,比如我用的連接配接池是druid,就需要自己改配置(如果就用c3p0就不需要改)

Druid連接配接池Quartz的工具類

DruidConnectionProvider

package com.li.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、需要配置我們的JobFactory,因為我們在項目開發中是需要在Job中操作資料庫的,那麼當然需要把它交給spring管理,但是quartz本身是不支援的,是以我們需要修改它的底層代碼,讓我們的Job類能被spring所管理

MyJobFactory

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

           

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.li.quartz02.utils.DruidConnectionProvider
org.quartz.dataSource.qzDS.driver: com.mysql.jdbc.Driver
org.quartz.dataSource.qzDS.URL: jdbc:mysql://localhost:3306/xm?useUnicode=true&characterEncoding=utf8
org.quartz.dataSource.qzDS.user: root
org.quartz.dataSource.qzDS.password: 123
org.quartz.dataSource.qzDS.maxConnection: 10

           

配置類

QuartzConfiguration

剛剛的配置也加在這裡面

package com.li.quartz02.config;

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

mybatis逆向生成

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:\\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.li.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.li.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.li.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_mvc_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" 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/xm?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
           

案例

讀取資料庫來開啟定時任務

建立兩張表,通過這兩張表和Quartz的内置表來管理動态的定時任務,表裡面的資料我們測試用的資料

t_schedule_trigger,管理具體的任務,

id:辨別列

cron:表達式

status(0關閉,1開啟)是否開啟

job_name:job的name

job_group:job的group

springboot內建quartz
springboot內建quartz

mybatis逆向生成這兩張表的實體類和mapper

job類

package com.li.quartz02.job;

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.err.println("MyJob是一個空的任務計劃,時間:"+new Date().toLocaleString());
    }
}
           
package com.li.quartz02.job;


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

import java.util.Date;

@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());
    }
}
           
package com.li.quartz02.job;


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

import java.util.Date;

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

service層

ScheduleTriggerServiceImpl

package com.li.quartz02.service.impl;

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

    @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.out.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();
        }
    }

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

ScheduleTriggerService

package com.li.quartz02.service;

import com.li.quartz02.model.ScheduleTrigger;

import java.util.List;


public interface ScheduleTriggerService {

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

controller層

QuartzController

package com.li.quartz02.controller;

import com.li.quartz02.model.ScheduleTrigger;
import com.li.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.queryScheduleTriggerLst();
        mv.addObject("list",list);
        mv.setViewName("index");
        return mv;
    }

    @RequestMapping("/edit")
    public String editStatus(ScheduleTrigger scheduleTrigger){
        int n = scheduleTriggerService.updateByPrimaryKeySelective(scheduleTrigger);
        return "redirect:/quartz/list";
    }

    @RequestMapping("/add")
    public String addStatus(ScheduleTrigger scheduleTrigger){
        int n = scheduleTriggerService.insert(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);
        if (id==0){
            mv.setViewName("add");
        }else {
            mv.setViewName("edit");
        }
        return mv;
    }

}
           

templates模闆頁面

index

<!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>
<a th:href="@{'/quartz/proSave/0'}">增加</a>
<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 : ${list}">
        <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>
           

edit

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>編輯</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>

           

add

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>增加</title>
</head>
<body>
<h1>增加</h1>
<form th:action="@{/quartz/add}" method="post">
    <input type="hidden" name="id" />
    任務表達式: <input width="300px" type="text" name="cron" /></br>
    job工作類: <input width="300px" type="text" name="job_name" /></br>
    job分組:<input width="300px" type="text" name="job_group" /></br>
    <input type="submit" value="送出"/>
</form>
</body>
</html>

           

ScheduleTriggerMapper.xml中修改了一點。。。

效果:

這樣就實作了頁面控制定時任務…

springboot內建quartz
springboot內建quartz
springboot內建quartz

繼續閱讀