Quartz之数据库存储

一、搭建项目

1、新建项目

2、在启动类Quartz02Application开启定时任务 

//开启定时任务
@EnableScheduling

3、新建任务类

MyJob :

package com.lv.code.job;

import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

public class MyJob implements Job {
    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
       JobDataMap data=context.getJobDetail().getJobDataMap();
        System.out.println(data.get("name")+"在搞"+data.get("loc")+"卫生");
    }



}

4、测试

package com.lv.code;

import com.lv.code.job.MyJob;
import org.junit.jupiter.api.Test;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.scheduling.annotation.Scheduled;

import static org.quartz.JobBuilder.newJob;

@SpringBootTest
class Quartz02ApplicationTests {

    @Test
    void contextLoads() throws Exception {
//        调度器 Scheduler
        SchedulerFactory factory=new StdSchedulerFactory();
        Scheduler scheduler=factory.getScheduler();
//        任务  Job
        JobDetail jobDetail=newJob(MyJob.class)
                .withIdentity("a","b")
                .withDescription("搞卫生")
//                .usingJobData("name","张三")
//                .usingJobData("loc","厕所")
                .build();
        jobDetail.getJobDataMap().put("name","张三");
        jobDetail.getJobDataMap().put("loc","厕所");
//        触发器  Trigger
        CronTrigger trigger=TriggerBuilder.newTrigger()
                .withIdentity("a","b")
                .withDescription("每秒打扫一次卫生")
                .withSchedule(CronScheduleBuilder.cronSchedule("* * * * * ?"))
                .build();
//        放到调度器中
        scheduler.scheduleJob(jobDetail,trigger);
//        开启调度
        scheduler.start();
    }

}

二、数据库解析

 1、到quartz官网中下载

quartz官网

 2、解压

文件中有许多数据库脚本,找到mysql.sql的脚本

 3、运行此脚本到数据库

 此期内容只会用到三张表:qrtz_cron_triggers、qrtz_job_details、qrtz_triggers

 4、到控制台运行以下触发器的表脚本

create table t_schedule_trigger
(
    id          bigint primary key auto_increment comment '触发器编号',
    cron        varchar(200) not null comment '触发器表达式',
    status      char(1)          not null comment '触发器状态: 禁用 启用',
    job_name    varchar(200) not null comment '任务名称: 存放的任务类的全路径',
    job_group   varchar(200) not null comment '任务所处分组',
    job_description varchar(200) not null comment '任务描述',
	trigger_description varchar(200) not null comment '触发器描述',
    unique index (job_name, job_group) comment '通过jobName和jobGroup来确定trigger的唯一性,所以这两列为联合唯一索引'
);

create table t_schedule_trigger_data
(
    id         bigint primary key auto_increment comment '数据编号',
    name       varchar(200) not null comment '对应的数据名称',
    value      varchar(512) comment '对应的数据值',
    trigger_id bigint       not null comment '外键: 引用t_schedule_trigger(id)',
    foreign key (trigger_id) references t_schedule_trigger (id)
);

在t_schedule_trigger表内添加一条数据:

 在t_schedule_trigger_data表内添加任务所对应的数据:

三、工具类解析

1、引用连接池

Ⅰ、导入依赖:此处直接覆盖pom文件依赖

 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-quartz</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-freemarker</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.2.8</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>tk.mybatis</groupId>
            <artifactId>mapper-spring-boot-starter</artifactId>
            <version>2.0.2</version>
        </dependency>
        <dependency>
            <groupId>javax.persistence</groupId>
            <artifactId>persistence-api</artifactId>
            <version>1.0</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

Ⅱ、Druid连接池的Quartz扩展类:帮助连接Druid连接池

package com.lv.code.util;

import com.alibaba.druid.pool.DruidDataSource;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.SneakyThrows;
import org.quartz.utils.ConnectionProvider;

import java.sql.Connection;

/*
#============================================================================
# JDBC
#============================================================================
org.quartz.jobqzDS.connectionProvider.class:com.zking.q03.quartz.DruidConnectionProvider
org.quartz.dataSourStore.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.ce.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扩展类
 *
 * @author hgh
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
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;

    @Override
    @SneakyThrows
    public Connection getConnection() {
        return datasource.getConnection();
    }

    @Override
    public void shutdown() {
        datasource.close();
    }

    @Override
    @SneakyThrows
    public void initialize() {
        assert this.URL != null : "DB URL cannot be null";
        assert this.driver != null : "DB driver class name cannot be null!";
        assert this.maxConnection > 0 : "Max connections must be greater than zero!";

        datasource = new DruidDataSource();
        datasource.setDriverClassName(this.driver);
        datasource.setUrl(this.URL);
        datasource.setUsername(this.user);
        datasource.setPassword(this.password);
        datasource.setMaxActive(this.maxConnection);
        datasource.setMinIdle(1);
        datasource.setMaxWait(0);
        datasource.setMaxPoolPreparedStatementPerConnectionSize(DruidConnectionProvider.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);
        }
    }

}

Ⅲ、让quartz与spring进行交互类:

Spring 提供了一种机制,能够为第三方框架赋能,让Spring管理的Bean去装配和填充那些不被Spring托管的Bean,这种机制叫AutowireCapableBeanFactory。目前了解到的有两款著名的开源框架Junit与Quartz借用了这种机制为自己赋能,达到更好地与Spring契合协作的目的,也从他们的整合姿势中学习到,当我们需要设计一个框架,而且需要拥抱Spring生态,为框架使用者提供更便利的无缝整合,需以微内核 + 插件机制思想,由内核层想办法拿到AutowireCapableBeanFactory,并在构造插件的时候,借助AutowireCapableBeanFactory去为插件赋能,做到无限扩展的可能性

package com.lv.code.util;

import lombok.SneakyThrows;
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;

/**
 * @author hgh
 */
@Component
@Slf4j
//让quartz与spring进行交互
public class MyJobFactory extends AdaptableJobFactory {

    private final AutowireCapableBeanFactory autowireCapableBeanFactory;

    @Autowired
    public MyJobFactory(AutowireCapableBeanFactory autowireCapableBeanFactory) {
        this.autowireCapableBeanFactory = autowireCapableBeanFactory;
    }

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

}

Ⅳ、配置类

QuartzConfiguration :使spring与quartz互通

package com.lv.code.conf;

import com.lv.code.util.MyJobFactory;
import lombok.SneakyThrows;
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.util.Properties;

/**
 * @author hgh
 */
@Configuration
public class QuartzConfiguration {

    private final MyJobFactory myJobFactory;

    @Autowired
    public QuartzConfiguration(MyJobFactory myJobFactory) {
        this.myJobFactory = myJobFactory;
    }

    /**
     * 创建调度器工厂
     */
    @Bean
    public SchedulerFactoryBean schedulerFactoryBean() {
        //1.创建SchedulerFactoryBean
        SchedulerFactoryBean factoryBean = new SchedulerFactoryBean();
        //2.加载自定义的quartz.properties配置文件
        factoryBean.setQuartzProperties(quartzProperties());
        //3.设置MyJobFactory
        factoryBean.setJobFactory(myJobFactory);
        return factoryBean;
    }

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

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

}

Ⅴ、创造连接池

#
#============================================================================
# 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,\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(\u5982\u679C\u9879\u76EE\u53EA\u90E8\u7F72\u5230 \u4E00\u53F0\u670D\u52A1\u5668,\u5C31\u4E0D\u7528\u4E86)
org.quartz.jobStore.isClustered=true
#============================================================================
# Configure Datasources
#============================================================================
#\u914D\u7F6E\u6570\u636E\u5E93\u6E90\uFF08org.quartz.dataSource.qzDS.maxConnections: c3p0\u914D\u7F6E\u7684\u662F\u6709s\u7684,druid\u6570\u636E\u6E90\u6CA1\u6709s\uFF09
org.quartz.dataSource.qzDS.connectionProvider.class:com.lv.code.util.DruidConnectionProvider
org.quartz.dataSource.qzDS.driver:com.mysql.cj.jdbc.Driver
org.quartz.dataSource.qzDS.URL:jdbc:mysql://127.0.0.1:3306/aaa?useUnicode=true&serverTimezone=Asia/Shanghai&useSSL=false&characterEncoding=utf-8
org.quartz.dataSource.qzDS.user:root
org.quartz.dataSource.qzDS.password:123456
org.quartz.dataSource.qzDS.maxConnection:10

Ⅵ、yml配置

application.yml:

server:
  port: 8080
spring:
  datasource:
    username: root
    password: 123456
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/aaa?userSSL=false&serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&allowPublicKeyRetrieval=true
    type: com.alibaba.druid.pool.DruidDataSource
    druid:
      initial-size: 5                                       # 初始化大小
      min-idle: 10                                          # 最小连接数
      max-active: 20                                        # 最大连接数
      max-wait: 60000                                       # 获取连接时的最大等待时间
      min-evictable-idle-time-millis: 300000                # 一个连接在池中最小生存的时间,单位是毫秒
      time-between-eviction-runs-millis: 60000              # 多久才进行一次检测需要关闭的空闲连接,单位是毫秒
      filters: stat                                         # 配置扩展插件:stat-监控统计,log4j-日志,wall-防火墙(防止SQL注入),去掉后,监控界面的sql无法统计   ,wall
      validation-query: SELECT 1                            # 检测连接是否有效的 SQL语句,为空时以下三个配置均无效
      test-on-borrow: true                                  # 申请连接时执行validationQuery检测连接是否有效,默认true,开启后会降低性能
      test-on-return: true                                  # 归还连接时执行validationQuery检测连接是否有效,默认false,开启后会降低性能
      test-while-idle: true                                 # 申请连接时如果空闲时间大于timeBetweenEvictionRunsMillis,执行validationQuery检测连接是否有效,默认false,建议开启,不影响性能
      stat-view-servlet:
        enabled: true                                       # 是否开启 StatViewServlet
        allow: 127.0.0.1                                    # 访问监控页面 白名单,默认127.0.0.1
        deny: 192.168.56.1                                  # 访问监控页面 黑名单
        login-username: admin                               # 访问监控页面 登陆账号
        login-password: 123                                 # 访问监控页面 登陆密码
      filter:
        stat:
          enabled: true                                     # 是否开启 FilterStat,默认true
          log-slow-sql: true                                # 是否开启 慢SQL 记录,默认false
          slow-sql-millis: 5000                             # 慢 SQL 的标准,默认 3000,单位:毫秒
          merge-sql: false                                  # 合并多个连接池的监控数据,默认false
  application:
    name: quartz02
logging:
  level:
    com.lv.code.mapper: debug

四、数据库存储开发

1、读取数据库数据到内存

Ⅰ、实体类

package com.lv.code.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import tk.mybatis.mapper.annotation.KeySql;

import javax.persistence.Column;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 * @author hgh
 */
@AllArgsConstructor
@NoArgsConstructor
@Data
@Accessors(chain = true)
@Table(name = "t_schedule_trigger")
public class ScheduleTrigger {

    @Id
    @KeySql(useGeneratedKeys = true)
    @Column(name = "id")
    private Long id;

    @Column(name = "cron")
    private String cron;

    @Column(name = "status")
    private String status;

    @Column(name = "job_name")
    private String jobName;

    @Column(name = "job_group")
    private String jobGroup;

    @Column(name = "job_description")
    private String jobDescription;

    @Column(name = "trigger_description")
    private String triggerDescription;

}
package com.lv.code.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import tk.mybatis.mapper.annotation.KeySql;

import javax.persistence.Column;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 * @author hgh
 */
@AllArgsConstructor
@NoArgsConstructor
@Data
@Accessors(chain = true)
@Table(name = "t_schedule_trigger_data")
public class ScheduleTriggerData {

    @Id
    @KeySql(useGeneratedKeys = true)
    @Column(name = "id", nullable = false)
    private Long id;

    @Column(name = "name")
    private String name;

    @Column(name = "value")
    private String value;

    @Column(name = "trigger_id")
    private Long triggerId;

}

Ⅱ、mapper层

ScheduleTriggerMapper :

package com.lv.code.mapper;

import com.lv.code.pojo.ScheduleTrigger;
import org.springframework.stereotype.Repository;
import tk.mybatis.mapper.common.Mapper;

@Repository
public interface ScheduleTriggerMapper extends Mapper<ScheduleTrigger> {

}

ScheduleTriggerDataMapper : 

package com.lv.code.mapper;

import org.springframework.stereotype.Repository;
import com.lv.code.pojo.ScheduleTriggerData;
import tk.mybatis.mapper.common.Mapper;
@Repository
public interface ScheduleTriggerDataMapper extends Mapper<ScheduleTriggerData> {

}

Ⅴ、在启动类加载mapper类

@MapperScan("com.lv.code.mapper")

Ⅵ、service层

ScheduleTriggerDataService :

package com.lv.code.service;

import com.lv.code.pojo.ScheduleTriggerData;

import java.util.List;

public interface ScheduleTriggerDataService {

    List<ScheduleTriggerData> find(Long triggerId);

}

ScheduleTriggerService :

package com.lv.code.service;

import com.lv.code.pojo.ScheduleTrigger;

import java.util.List;

public interface ScheduleTriggerService {

    List<ScheduleTrigger> find();

}

Ⅶ、实现接口

ScheduleTriggerDataServiceImpl :

package com.lv.code.service;

import com.lv.code.pojo.ScheduleTriggerData;
import com.lv.code.pojo.ScheduleTriggerData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

@Service
public class ScheduleTriggerDataServiceImpl implements ScheduleTriggerDataService {

    @Autowired
    private ScheduleTriggerDataMapper mapper;

    @Override
    public List<ScheduleTriggerData> find(Long triggerId) {
        Example example=new Example(ScheduleTriggerData.class);
        example.createCriteria().andEqualTo("triggerId",triggerId);
        return mapper.selectByExample(example);
    }
}

ScheduleTriggerServiceImpl :

package com.lv.code.service;

import com.lv.code.mapper.ScheduleTriggerMapper;
import com.lv.code.pojo.ScheduleTrigger;
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 mapper;

    @Override
    public List<ScheduleTrigger> find() {
        return mapper.selectAll();
    }
}

Ⅷ、quartz任务类

package com.lv.code.util;

import com.lv.code.job.MyJob;
import com.lv.code.pojo.ScheduleTrigger;
import com.lv.code.pojo.ScheduleTriggerData;
import com.lv.code.service.ScheduleTriggerDataService;
import com.lv.code.service.ScheduleTriggerService;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import static org.quartz.JobBuilder.newJob;

@Component
public class QuartzTask {

    private ScheduleTriggerService triggerService;
    private ScheduleTriggerDataService dataService;
    private Scheduler scheduler;

//    构造器
    @Autowired
    public QuartzTask(ScheduleTriggerService triggerService, ScheduleTriggerDataService dataService,Scheduler scheduler) {
        this.triggerService = triggerService;
        this.dataService = dataService;
        this.scheduler=scheduler;
    }


    @Scheduled(cron = "0/10 * * * * ?")
    public void register() throws Exception {
//        去数据库查看自己建的表是否具有变化
//        查询数据库中所有的任务
        for (ScheduleTrigger t:triggerService.find()){
//            判断这个任务是否以及被quartz管理了
//           拿到这个任务的名字和分组
            String jobName=t.getJobName();
            String jobGroup=t.getJobGroup();
            String jobDescription=t.getJobDescription();
            String triggerDescription=t.getTriggerDescription();
            String cron=t.getCron();
//            生成一个Key,去调度器中拿到对应的元素
            CronTrigger trigger=(CronTrigger)scheduler.getTrigger(TriggerKey.triggerKey(jobName,jobGroup));
            if(trigger==null){
//          在自己的表里面有,但是quartz没有管理它

//           禁用
            if("0".equals(t.getStatus())){
                continue;
            }
//            新建(将任务放到quartz中)
                JobDetail jobDetail=newJob((Class<? extends Job>) Class.forName(jobName))
                        .withIdentity(jobName,jobGroup)
                        .withDescription(jobDescription)
                        .build();
//            读取任务所需要的数据
                for (ScheduleTriggerData data : dataService.find(t.getId())){
//                    将所需任务数据放到任务中
                    jobDetail.getJobDataMap().put(data.getName(),data.getValue());
                }
//        触发器  Trigger
                trigger=TriggerBuilder.newTrigger()
                        .withIdentity(jobName,jobGroup)
                        .withDescription(triggerDescription)
                        .withSchedule(CronScheduleBuilder.cronSchedule(cron))
                        .build();
//            分配给调度器
                scheduler.scheduleJob(jobDetail,trigger);
                continue;
            }
//            任务已经在quartz中有
            if("0".equals(t.getStatus())){
//                在quartz中删除掉那个任务
                scheduler.deleteJob(JobKey.jobKey(jobName,jobGroup));
                continue;
            }
//           任务存在,而且不是禁用状态
//            判断表达式是被修改了
            if (trigger.getCronExpression().equals(cron)){
//                新建(将任务放到quartz中)
                JobDetail jobDetail=newJob((Class<? extends Job>) Class.forName(jobName))
                        .withIdentity(jobName,jobGroup)
                        .withDescription(jobDescription)
                        .build();
//            读取任务所需要的数据
                for (ScheduleTriggerData data : dataService.find(t.getId())){
//                    将所需任务数据放到任务中
                    jobDetail.getJobDataMap().put(data.getName(),data.getValue());
                }
//        触发器  Trigger
                trigger=TriggerBuilder.newTrigger()
                        .withIdentity(jobName,jobGroup)
                        .withDescription(triggerDescription)
                        .withSchedule(CronScheduleBuilder.cronSchedule(cron))
                        .build();
//                让调度器更换触发器
                scheduler.rescheduleJob(TriggerKey.triggerKey(jobName,jobGroup),trigger);
            }
        }


    }

}

 qrtz_cron_triggers、qrtz_job_details、qrtz_triggers都有数据:

 


四、完善

删除了自己建的表(t_schedule_trigger)的数据,同时程序依旧在运行,只有删除quartz(qrtz_cron_triggers)中表的数据才会停止。

1、解决:不可能什么都在数据库中操作,因此写一个界面(index.ftl)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap-theme.min.css">
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body class="container">
<h1>定时任务情况</h1>
<table class="table table-condensed">
    <tr>
        <td>表达式</td>
        <td>名字(执行类名)</td>
        <td>分组</td>
        <td>任务描述</td>
        <td>触发器描述</td>
        <td>状态</td>
        <td>操作</td>
    </tr>
    <#list triggers as trigger>
        <tr>
            <td>${trigger.cron!""}</td>
            <td>${trigger.jobName!""}</td>
            <td>${trigger.jobGroup!""}</td>
            <td>${trigger.jobDescription!""}</td>
            <td>${trigger.triggerDescription!""}</td>
            <td>${(trigger.status=='0')?string("已禁用","启用中")}</td>
            <td>
                <a href="/delete?triggerId=${trigger.id}" class="btn btn-danger">关闭</a>
                <a class="btn btn-warning">修改</a>
            </td>
        </tr>
    </#list>
</table>
<div class="jumbotron">
    <h2>新增定时任务</h2>
    <form method="post" action="insert">
        <div class="form-group">
            <label for="jobName">任务名称(执行类名)</label>
            <input class="form-control" id="jobName" name="jobName" value="com.yk.code.job.Job01">
        </div>
        <div class="form-group">
            <label for="jobGroup">任务分组</label>
            <input class="form-control" id="jobGroup" name="jobGroup">
        </div>
        <div class="form-group">
            <label for="cron">任务表达式</label>
            <input class="form-control" id="cron" name="cron" value="* * * * * ?">
        </div>
        <div class="form-group">
            <label for="jobDescription">任务描述</label>
            <input class="form-control" id="description" name="jobDescription">
        </div>
        <div class="form-group">
            <label for="triggerDescription">触发器描述</label>
            <input class="form-control" id="description" name="triggerDescription">
        </div>
        <div style="border: 1px solid black;border-radius: 10px;padding: 20px;margin-bottom: 10px;">
            <h3>任务参数</h3>
            <div id="ps"></div>
            <br>
            <button type="button" onclick="insert_attr()" class="btn btn-primary">增加</button>
        </div>
        <div class="form-group">
            <label class="radio-inline">
                <input type="radio" name="status" value="0" checked> 禁用
            </label>
            <label class="radio-inline">
                <input type="radio" name="status" value="1"> 启用
            </label>
        </div>
        <button type="submit" class="btn btn-default">确定</button>
    </form>
    <script>

        let node_text =
            `<div class="form-inline" style="margin: 3px 0px;">
                <div class="form-group">
                    <input class="form-control" onchange="setAttrName(this)" placeholder="attribute">
                </div>
                <div class="form-group">
                    <input class="form-control" placeholder="value">
                </div>
            </div>`;

        function insert_attr() {
            $("#ps").append(node_text);
        }

        function setAttrName(obj) {
            $(obj).parents(".form-inline").find("input").eq(1).attr("name", obj.value)
        }

    </script>
</div>
</body>
</html>

2、增加任务触发器ScheduleTrigger与任务数据的方法

Ⅰ、ScheduleTriggerService—ScheduleTriggerDataService:

int insert(ScheduleTrigger trigger);
int insert(ScheduleTriggerData data);

Ⅱ、实现方法:ScheduleTriggerServiceImpl—ScheduleTriggerServiceDataImpl

    @Override
    public int insert(ScheduleTrigger trigger) {
        return mapper.insert(trigger);
    }
}
   @Override
    public int insert(ScheduleTriggerData data) {
        return mapper.insert(data);
    }

3、controller层

package com.lv.code.Controller;

import com.lv.code.pojo.ScheduleTrigger;
import com.lv.code.pojo.ScheduleTriggerData;
import com.lv.code.service.ScheduleTriggerDataService;
import com.lv.code.service.ScheduleTriggerService;
import org.quartz.Scheduler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;


import javax.servlet.http.HttpServletRequest;

/**
 * @author T440s
 */
@Controller
public class QuartzController {
    private ScheduleTriggerService triggerService;
    private ScheduleTriggerDataService dataService;
    private Scheduler scheduler;

    @Autowired
    public QuartzController(ScheduleTriggerService triggerService, ScheduleTriggerDataService dataService, Scheduler scheduler) {
        this.triggerService = triggerService;
        this.dataService = dataService;
        this.scheduler = scheduler;
    }

    @GetMapping("/")
    public String index(Model model){
        model.addAttribute("triggers",triggerService.find());
        return "index";
    }

    @PostMapping("/insert")
    public String insert(ScheduleTrigger trigger, HttpServletRequest request){
        int i=triggerService.insert(trigger);
        if(i>0){
            request.getParameterMap().forEach((a,b)->{
                try {
//                    判断是否是类的属性
                    ScheduleTrigger.class.getDeclaredField(a);
                }catch (NoSuchFieldException e){
                    ScheduleTriggerData data=
                            new ScheduleTriggerData()
                                    .setName(a)
                                    .setValue(b[0])
                                    .setTriggerId(trigger.getId());
                    dataService.insert(data);
                }
            });
        }
        return "redirect:/";
    }


}

本期内容结束~~~~

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
对于Quartz数据库配置,你需要执行以下步骤: 1. 确保已经创建了一个用于存储Quartz调度表的数据库。你可以使用例如MySQL或PostgreSQL等关系型数据库。 2. 在你的项目中添加Quartz的相关依赖。你可以通过Maven或Gradle等构建工具来添加依赖。例如,如果你使用Maven,可以在`pom.xml`文件中添加以下依赖: ```xml <dependency> <groupId>org.quartz-scheduler</groupId> <artifactId>quartz</artifactId> <version>2.3.2</version> </dependency> ``` 3. 在你的项目中创建一个Quartz配置文件。你可以创建一个名为`quartz.properties`的文件,并将其放置在类路径下。在该配置文件中,你需要指定使用的数据库类型、连接信息以及其他相关的配置项。以下是一个示例配置文件: ```properties # 数据库类型 org.quartz.jobStore.driverDelegateClass = org.quartz.impl.jdbcjobstore.StdJDBCDelegate org.quartz.jobStore.dataSource = myDS # 数据库连接信息 org.quartz.dataSource.myDS.driver = com.mysql.jdbc.Driver org.quartz.dataSource.myDS.URL = jdbc:mysql://localhost:3306/quartz org.quartz.dataSource.myDS.user = root org.quartz.dataSource.myDS.password = password # 其他配置项... ``` 请根据你使用的数据库类型和实际情况修改上述配置。 4. 在你的代码中加载Quartz配置。在应用程序启动时,你需要加载上述的Quartz配置文件。以下是一个示例的Java代码: ```java import org.quartz.Scheduler; import org.quartz.SchedulerException; import org.quartz.impl.StdSchedulerFactory; public class QuartzExample { public static void main(String[] args) { try { // 加载Quartz配置 Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler(); // 启动调度器 scheduler.start(); // 其他操作... // 关闭调度器 scheduler.shutdown(); } catch (SchedulerException e) { e.printStackTrace(); } } } ``` 在这个示例中,我们使用`StdSchedulerFactory`类来加载Quartz配置并创建调度器实例。然后,你可以根据需要进行其他操作,最后记得关闭调度器。 这就是Quartz数据库配置的基本步骤。根据你的实际需求,你可能还需要了解更多关于Quartz的使用方法和其他配置项。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值