springboot与quartz整合

目录

  • 前言
    • pom配置文件
      • pom.xml配置
    • resources配置文件
      • application.yml
      • quartz.properties
    • quartz整合文件
      • MySql: quartz必用核心数据库
      • Druid: 改变quartz默认的数据源(不是druid数据源的就不用了)
      • config: 配置自己的quartz文件(需要spring帮忙)
    • 使用案例
      • quartzController
      • ScheduleTriggerServiceImpl
      • 案例展示
  • 后记(配置文件和定时任务原理)

前言

本次是关于quartz如何整合的一个案例,操作定时任务如何更新,

这个的整合可以先看一看此次所需的文件结构:
springboot与quartz整合_第1张图片

pom配置文件

pom.xml配置

这个只是quartz所需的包

		<!--spring整合所没有的部分-->
        <dependency>
            <groupId>org.quartz-scheduler</groupId>
            <artifactId>quartz-jobs</artifactId>
            <version>2.2.1</version>
        </dependency>
        <!--被spring整合后的并加了些其他东西-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-quartz</artifactId>
        </dependency>

总的一个配置可以看看没事,我都打好了注解:


<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.0modelVersion>
    <parent>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-parentartifactId>
        <version>2.2.1.RELEASEversion>
        <relativePath/> 
    parent>
    <groupId>com.liwangwanggroupId>
    <artifactId>quartz02artifactId>
    <version>0.0.1-SNAPSHOTversion>
    <name>quartz02name>
    <description>Demo project for Spring Bootdescription>

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

    <dependencies>
        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-jdbcartifactId>
        dependency>
        
        <dependency>
            <groupId>org.quartz-schedulergroupId>
            <artifactId>quartz-jobsartifactId>
            <version>2.2.1version>
        dependency>
        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-quartzartifactId>
        dependency>

        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-thymeleafartifactId>
        dependency>
        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>
        
        <dependency>
            <groupId>org.mybatis.spring.bootgroupId>
            <artifactId>mybatis-spring-boot-starterartifactId>
            <version>2.1.1version>
        dependency>
        
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>${mysql.version}version>
            <scope>runtimescope>
        dependency>
        
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <optional>trueoptional>
        dependency>
        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintagegroupId>
                    <artifactId>junit-vintage-engineartifactId>
                exclusion>
            exclusions>
        dependency>
        
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>druid-spring-boot-starterartifactId>
            <version>1.1.10version>
        dependency>
        
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-aspectsartifactId>
        dependency>
        
        <dependency>
            <groupId>com.github.pagehelpergroupId>
            <artifactId>pagehelperartifactId>
            <version>5.1.2version>
            <scope>compilescope>
        dependency>


    dependencies>

    <build>
        <resources>
            <resource>
                <directory>src/main/javadirectory>
                <includes>
                    <include>**/*.xmlinclude>
                includes>
            resource>
        resources>

        <plugins>
            <plugin>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-maven-pluginartifactId>
            plugin>
        plugins>
    build>

project>

resources配置文件

springboot与quartz整合_第2张图片

application.yml

server:
  port: 80
  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/context?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: 127.0.0.1
        #deny: 192.168.1.100


#pagehelper\u5206\u9875\u63D2\u4EF6\u914D\u7F6E
pagehelper:
  helperDialect: mysql
  reasonable: true
  supportMethodsArguments: true
  params: count=countSql
#\u663E\u793A\u65E5\u5FD7
logging:
  level:
    com.liwangwang.quartz02.mapper: debug



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

quartz整合文件

springboot与quartz整合_第3张图片

MySql: quartz必用核心数据库

去官网下载包,比如我的是一个quartz-2.2.3
官网http://www.quartz-scheduler.org/downloads/

springboot与quartz整合_第4张图片
springboot与quartz整合_第5张图片

Druid: 改变quartz默认的数据源(不是druid数据源的就不用了)

springboot与quartz整合_第6张图片
DruidConnectionProvider.java

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

springboot与quartz整合_第7张图片

config: 配置自己的quartz文件(需要spring帮忙)

springboot与quartz整合_第8张图片
有了这个后是让spring去帮忙注入
MyJobFactory.java

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

QuartzConfiguration.java

package com.liwangwang.quartz02.quartz;

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

springboot与quartz整合_第9张图片
springboot与quartz整合_第10张图片

使用案例

重点文件,其他的都放包下,去下载吧,

quartzController

package com.liwangwang.quartz02.controller;

import com.liwangwang.quartz02.model.ScheduleTrigger;
import com.liwangwang.quartz02.service.ScheduleTriggerService;
import com.liwangwang.quartz02.utils.PageBean;
import com.liwangwang.quartz02.utils.PageUtil;
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 javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @authorliwangwang
 * @site www.liwangwang.com
 * @company xxx公司
 * @create 2019-11-15 18:13
 */
@Controller
@RequestMapping("quartz")
public class quartzController {

    @Autowired
    ScheduleTriggerService scheduleTriggerService;


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


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

        return modelAndView;
    }

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


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

    @RequestMapping("/del/{bid}")
    public String del(@PathVariable(value = "bid") Integer bid){
        scheduleTriggerService.deleteByPrimaryKey(bid);
        scheduleTriggerService.refreshScheduler();
        return "redirect:/quartz/listPager";
    }
}

ScheduleTriggerServiceImpl

package com.liwangwang.quartz02.service.impl;

import com.liwangwang.quartz02.mapper.ScheduleTriggerMapper;
import com.liwangwang.quartz02.mapper.ScheduleTriggerParamMapper;
import com.liwangwang.quartz02.model.ScheduleTrigger;
import com.liwangwang.quartz02.model.ScheduleTriggerParam;
import com.liwangwang.quartz02.service.ScheduleTriggerService;
import com.liwangwang.quartz02.utils.PageBean;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ScheduleTriggerServiceImpl implements ScheduleTriggerService {

    @Autowired
    private ScheduleTriggerMapper scheduleTriggerMapper;

    @Autowired
    private ScheduleTriggerParamMapper scheduleTriggerParamMapper;

    @Autowired
    private Scheduler scheduler;

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

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

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

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

    @Override
    public int refreshScheduler(){
        int a = 0;
        try {
            List<ScheduleTrigger> scheduleTriggers =
                    scheduleTriggerMapper.queryScheduleTriggerLstPager(null);
            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();
        }
        return a ;
    }

    @Override
    public List<ScheduleTrigger> queryScheduleTriggerLstPager(ScheduleTrigger scheduleTrigger,PageBean pageBean) {
        return scheduleTriggerMapper.queryScheduleTriggerLstPager(scheduleTrigger);
    }
}

案例展示

比如我做的一个案例:
springboot与quartz整合_第11张图片
springboot与quartz整合_第12张图片

springboot与quartz整合_第13张图片

后记(配置文件和定时任务原理)

稍微讲下配置文件和定时任务原理吧,
一、配置文件
总的配置文件分为管理数据源、管理scheduler生成的两个部分
springboot与quartz整合_第14张图片

1、管理数据源
其实上面就是我要用的数据源。
enn,只不过就算是之后的运用数据库我们也是用的是druid,如果不是druid的话就没有参考了

druid整合后多了一个quartz接受的整合文件,其实你不搞也行反正quartz内部用的就是c3p0的数据源。
通过定制在quartz.properties文件的配置就可以确定你用的是哪个数据源了
springboot与quartz整合_第15张图片

2、管理scheduler生成

这个就是去把调度器的生成交给spring进行一个管理

springboot与quartz整合_第16张图片
springboot与quartz整合_第17张图片

二、定时任务管理

在下载并运行quartz官方的数据库后就会有一些数据表
那么其实在整合完毕过后的quartz的运行就在使用官方的表,而不是去使用我们的表。
springboot与quartz整合_第18张图片

那么都知道在刚开始的时候官方的表都是空的,每当我们创建一个调度器的时候,其实在同时内部就会向官方表加入数据,此后只要开启服务quartz就会自动开启定时任务,
springboot与quartz整合_第19张图片

我们自己有张表可以显示自己的定时任务详情,那么我们如果就单独的改变自己的表那是没用的。所以我们需要操作官方表,官方表都是自己有方法的,所以我们在刷新,修改,增加,删除的时候都调用一下并检查一下官方表就行了。
详细看上面的ScheduleTriggerServiceImpl
springboot与quartz整合_第20张图片

项目
链接:https://pan.baidu.com/s/1Ltmlg7An9tM9xxG5ibfF7A
提取码:dnm4

你可能感兴趣的:(#,springboot,springboot,quartz)