Quartz 【数据库储存】

目录​​​​​​​

1. 导入pom依赖 

2. resources模块 

3. pojo模块

4. mapper模块

5. service模块

6. job模块

7. controller模块

8. config模块

9. utils模块

10. springboot启动类配置

11. 启动项目测试​​​​​​​


话不多说 直接上代码了

1. 导入pom依赖 

<!--所有依赖-->
    <dependencies>
        <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>
    </dependencies>

2. resources模块 

  2.1 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.jmh.quartz.utils.DruidConnectionProvider
org.quartz.dataSource.qzDS.driver:com.mysql.cj.jdbc.Driver
org.quartz.dataSource.qzDS.URL:jdbc:mysql://127.0.0.1:3306/boot?useUnicode=true&serverTimezone=Asia/Shanghai&useSSL=false&characterEncoding=utf-8
org.quartz.dataSource.qzDS.user:root
org.quartz.dataSource.qzDS.password:1234
org.quartz.dataSource.qzDS.maxConnection:10

配置数据库源下面代码需修改:

    1. 自己的Druid连接池类下面已提供

    2. 数据库 登录账号、密码

  2.2 application.yml

spring:
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/boot?useUnicode=true&serverTimezone=Asia/Shanghai&useSSL=false&characterEncoding=utf-8
    username: root
    password: 1234
    driver-class-name: com.mysql.jdbc.Driver
    #com.mysql.cj.jdbc.Driver
    #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
  freemarker:
    #指定HttpServletRequest的属性是否可以覆盖controller的model的同名项
    allow-request-override: false
    #req访问request
    request-context-attribute: req
    #后缀名freemarker默认后缀为.ftl,当然你也可以改成自己习惯的.html
    suffix: .ftl
    #设置响应的内容类型
    content-type: text/html;charset=utf-8
    #是否允许mvc使用freemarker
    enabled: true
    #是否开启template caching
    cache: false
    #设定模板的加载路径,多个以逗号分隔,默认: [“classpath:/templates/”]
    template-loader-path: classpath:/templates/
    #设定Template的编码
    charset: UTF-8
logging:
  level:
    com.jmh.quartz.mapper: debug

  需修改数据库连接

  2.3  resources/templates/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">
<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="exampleModalLabel">修改任务属性</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <#--数据部分-->
            <div class="modal-body">
                <form method="post" action="update">
                    <input name="triggerId" id="triggerId" type="hidden">
                    <div class="form-group">
                        <label for="exampleInputEmail1">name</label>
                        <input name="name" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp">
                    </div>
                    <div class="form-group">
                        <label for="exampleInputPassword1">loc</label>
                        <input name="loc"  class="form-control" id="exampleInputPassword1">
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                        <button type="submit" class="btn btn-primary">Save changes</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>
<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 onclick="updateId(${trigger.id})" class="btn btn-warning" data-toggle="modal" data-target="#exampleModal">修改</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.jmh.quartz.job.MyJob">
        </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="jobDescription" name="jobDescription">
        </div>
        <div class="form-group">
            <label for="triggerDescription">触发器描述</label>
            <input class="form-control" id="triggerDescription" 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)
        }

        function updateId(row) {
            $("#triggerId").val(row)
        }

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

3. pojo模块

  3.1 ​​​​​​​ScheduleTrigger

package com.jmh.quartz.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;
import java.io.Serializable;

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

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

}

  3.2 ScheduleTriggerData

package com.jmh.quartz.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;
import java.io.Serializable;

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

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

}

4. mapper模块

  4.1 ScheduleTriggerMapper

package com.jmh.quartz.mapper;

import com.jmh.quartz.pojo.ScheduleTrigger;
import org.springframework.stereotype.Repository;
import tk.mybatis.mapper.common.Mapper;

/**
 * @author 蒋明辉
 * @data 2022/10/31 14:39
 */
@Repository
public interface ScheduleTriggerMapper extends Mapper<ScheduleTrigger>{
}

  4.2 ScheduleTriggerDataMapper

package com.jmh.quartz.mapper;

import com.jmh.quartz.pojo.ScheduleTriggerData;
import org.springframework.stereotype.Repository;
import tk.mybatis.mapper.common.Mapper;

/**
 * @author 蒋明辉
 * @data 2022/10/31 14:39
 */
@Repository
public interface ScheduleTriggerDataMapper extends Mapper<ScheduleTriggerData> {
}

5. service模块

  5.1 IScheduleTriggerService

package com.jmh.quartz.service;

import com.jmh.quartz.pojo.ScheduleTrigger;
import com.jmh.quartz.pojo.ScheduleTriggerData;
import org.springframework.stereotype.Repository;
import tk.mybatis.mapper.common.Mapper;

import java.util.List;

/**
 * @author 蒋明辉
 * @data 2022/10/31 14:39
 */
public interface IScheduleTriggerService {

    List<ScheduleTrigger> find();

    int insert(ScheduleTrigger scheduleTrigger);

    int delete(Long triggerId);

    ScheduleTrigger findById(Long triggerId);
}

  5.2 IScheduleTriggerDataService

package com.jmh.quartz.service;

import com.jmh.quartz.pojo.ScheduleTriggerData;
import org.springframework.stereotype.Repository;
import tk.mybatis.mapper.common.Mapper;

import java.util.List;

/**
 * @author 蒋明辉
 * @data 2022/10/31 14:39
 */
public interface IScheduleTriggerDataService {

    List<ScheduleTriggerData> find(Long triggerId);

    int insert(ScheduleTriggerData scheduleTriggerData);

    int delete(Long trigger);

    int update(ScheduleTriggerData scheduleTriggerData);
}

 5.3 impl模块实现类

  •  ScheduleTriggerServiceImpl
package com.jmh.quartz.service.imp;

import com.jmh.quartz.mapper.ScheduleTriggerMapper;
import com.jmh.quartz.pojo.ScheduleTrigger;
import com.jmh.quartz.service.IScheduleTriggerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author 蒋明辉
 * @data 2022/10/31 14:48
 */
@Service
public class ScheduleTriggerServiceImpl implements IScheduleTriggerService {

    @Autowired
    private ScheduleTriggerMapper mapper;

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

    @Override
    public int insert(ScheduleTrigger scheduleTrigger) {
        return mapper.insert(scheduleTrigger);
    }

    @Override
    public int delete(Long triggerId) {
        return mapper.deleteByPrimaryKey(triggerId);
    }

    @Override
    public ScheduleTrigger findById(Long triggerId) {
        return mapper.selectByPrimaryKey(triggerId);
    }
}
  •  ScheduleTriggerDataServiceImpl
package com.jmh.quartz.service.imp;

import com.jmh.quartz.mapper.ScheduleTriggerDataMapper;
import com.jmh.quartz.pojo.ScheduleTriggerData;
import com.jmh.quartz.service.IScheduleTriggerDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

/**
 * @author 蒋明辉
 * @data 2022/10/31 14:51
 */
@Service
public class ScheduleTriggerDataServiceImpl implements IScheduleTriggerDataService {

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

    @Override
    public int insert(ScheduleTriggerData scheduleTriggerData) {
        return mapper.insert(scheduleTriggerData);
    }

    @Override
    public int delete(Long trigger) {
        //创建用例
        Example example=new Example(ScheduleTriggerData.class);
        //根据用例来创建一个条件
        example.createCriteria().andEqualTo("triggerId", trigger);
        return mapper.deleteByExample(example);
    }

    @Override
    public int update(ScheduleTriggerData scheduleTriggerData) {
        return mapper.updateByPrimaryKeySelective(scheduleTriggerData);
    }
}

6. job模块

  MyJob

package com.jmh.quartz.job;

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

/**
 * @author 蒋明辉
 * @data 2022/10/31 14:21
 */
public class MyJob implements Job {
    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        JobDataMap jobDataMap = context.getJobDetail().getJobDataMap();
        System.out.println(jobDataMap.get("name") + "正在" + jobDataMap.get("loc") + "努力的打扫卫生");
    }
}

7. controller模块

   QuartzController

package com.jmh.quartz.controller;

import com.jmh.quartz.pojo.ScheduleTrigger;
import com.jmh.quartz.pojo.ScheduleTriggerData;
import com.jmh.quartz.service.IScheduleTriggerDataService;
import com.jmh.quartz.service.IScheduleTriggerService;
import lombok.SneakyThrows;
import org.quartz.*;
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 org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

import static org.quartz.JobBuilder.newJob;

/**
 * @author hgh
 */
@Controller
public class QuartzController {

    private final IScheduleTriggerService triggerService;
    private final IScheduleTriggerDataService dataService;
    private final Scheduler scheduler;

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


    @GetMapping("/")
    public ModelAndView index() {
        ModelAndView model=new ModelAndView();
        model.addObject("triggers", triggerService.find());
        model.setViewName("index");
        return model;
    }

    @PostMapping("/insert")
    public String insert(ScheduleTrigger trigger, HttpServletRequest request) {
        //System.out.println("任务对象数据" + trigger);
        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:/";
    }

    @GetMapping("/delete")
    @SneakyThrows
    public String delete(Long triggerId) {
        //System.out.println("进来了并带来了参数" + triggerId);
        //根据任务编号查询单个
        ScheduleTrigger trigger = triggerService.findById(triggerId);
        //System.out.println("查询出来的任务" + trigger);
        //根据任务编号删除任务数据
        dataService.delete(triggerId);
        //根据任务编号删除任务
        triggerService.delete(triggerId);
        //删除quartz数据中的任务
        scheduler.deleteJob(JobKey.jobKey(trigger.getJobName(), trigger.getJobGroup()));
        return "redirect:/";
    }

    @PostMapping("update")
    @SneakyThrows
    public String update(ScheduleTriggerData trigger, HttpServletRequest request){
        List<ScheduleTriggerData> list=new ArrayList<>();
        //根据任务编号查询单个
        ScheduleTrigger byId = triggerService.findById(trigger.getTriggerId());
        //删除quartz数据中的任务
        scheduler.deleteJob(JobKey.jobKey(byId.getJobName(), byId.getJobGroup()));
        request.getParameterMap().forEach((a, b) -> {
            try {
                //判断是否是类的属性
                ScheduleTrigger.class.getDeclaredField(a);
            } catch (NoSuchFieldException e) {
                if(!"triggerId".equals(a)){
                    ScheduleTriggerData data =
                            new ScheduleTriggerData()
                                    .setName(a)
                                    .setValue(b[0])
                                    .setTriggerId(trigger.getId());
                    List<ScheduleTriggerData> data1 = dataService.find(trigger.getTriggerId());
                    for (ScheduleTriggerData scheduleTriggerData : data1) {
                        if(scheduleTriggerData.getName().equals(data.getName())){
                            scheduleTriggerData.setName(data.getName());
                            scheduleTriggerData.setValue(data.getValue());
                            list.add(scheduleTriggerData);
                        }
                    }
                }
            }
        });
        for (ScheduleTriggerData scheduleTriggerData : list) {
            //开始修改任务数据
            dataService.update(scheduleTriggerData);
        }
        //新建任务
        JobDetail jobDetail=newJob((Class<? extends Job>) Class.forName(byId.getJobName()))
                .withDescription(byId.getJobDescription())//任务描述
                .withIdentity(byId.getJobName(),byId.getJobGroup())//任务编号
                .build();
        for (ScheduleTriggerData data : dataService.find(byId.getId())) {
            //将所需要的任务数据传递到任务里面
            jobDetail.getJobDataMap().put(data.getName(),data.getValue());
        }
        //新建触发器
        Trigger tt = TriggerBuilder.newTrigger()
                .withDescription(byId.getJobDescription())
                .withIdentity(byId.getJobName(),byId.getJobGroup())
                .withSchedule(CronScheduleBuilder.cronSchedule(byId.getCron()))
                .build();
        //分配给调度器
        scheduler.scheduleJob(jobDetail,tt);
        return "redirect:/";
    }

}

8. config模块

  QuartzConfiguration

package com.jmh.quartz.config;

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

}

9. utils模块

  9.1 DruidConnectionProvider

package com.jmh.quartz.utils;

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

}

  9.2 MyJobFactory

package com.jmh.quartz.utils;

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

}

  9.3 QuartzTask

package com.jmh.quartz.utils;

import com.jmh.quartz.pojo.ScheduleTrigger;
import com.jmh.quartz.pojo.ScheduleTriggerData;
import com.jmh.quartz.service.IScheduleTriggerDataService;
import com.jmh.quartz.service.IScheduleTriggerService;
import lombok.SneakyThrows;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;

import static org.quartz.JobBuilder.newJob;

/**
 * @author 蒋明辉
 * @data 2022/10/31 14:58
 */
@Component
public class QuartzTask {

    @Autowired
    private IScheduleTriggerService triggerService;
    @Autowired
    private IScheduleTriggerDataService dataService;
    @Autowired
    private Scheduler scheduler;


    //每隔十秒触发一次
    @Scheduled(cron = "0/10 * * * * ?")
    @SneakyThrows
    public void register(){
        //查询所有任务
        for (ScheduleTrigger t : triggerService.find()) {
            //获取任务里面的名字分组
            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));
            //非空 代表quartz里面不存在
            if (null==trigger) {
                //禁用
                if("0".equals(t.getStatus())){
                    continue;
                }
                //新建任务
                JobDetail jobDetail=newJob((Class<? extends Job>) Class.forName(jobName))
                        .withDescription(jobDescription)//任务描述
                        .withIdentity(jobName,jobGroup)//任务编号
                        .build();
                //遍历任务数据
                for (ScheduleTriggerData data : dataService.find(t.getId())) {
                    //将所需要的任务数据传递到任务里面
                    jobDetail.getJobDataMap().put(data.getName(),data.getValue());
                }
                //新建触发器
                 trigger = TriggerBuilder.newTrigger()
                        .withDescription(triggerDescription)
                        .withIdentity(jobName,jobGroup)
                        .withSchedule(CronScheduleBuilder.cronSchedule(cron))
                        .build();
                //分配给调度器
                scheduler.scheduleJob(jobDetail,trigger);
                continue;
            }
            //代表quartz里面存在
            if("0".equals(t.getStatus())){
                //删除任务
                scheduler.deleteJob(JobKey.jobKey(jobName,jobGroup));
                continue;
            }
            //任务存在 判断表达式是否被修改
            if (!trigger.getCronExpression().equals(cron)) {
                trigger = TriggerBuilder.newTrigger()
                        .withDescription(triggerDescription)
                        .withIdentity(jobName,jobGroup)
                        .withSchedule(CronScheduleBuilder.cronSchedule(cron))
                        .build();
                //更新触发器
                scheduler.rescheduleJob(TriggerKey.triggerKey(jobName,jobGroup),trigger);
            }
        }
    }

}

10. springboot启动类配置

package com.jmh.quartz;

import org.apache.ibatis.annotations.Mapper;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
import tk.mybatis.spring.annotation.MapperScan;

@SpringBootApplication
@EnableScheduling
@MapperScan("com.jmh.quartz.mapper")
public class QuartzApplication {

    public static void main(String[] args) {
        SpringApplication.run(QuartzApplication.class, args);
    }

}

如果对下篇这篇文章感兴趣的话可复制下面路径前往小编gitee仓库获取源代码和数据库文件可在自己的电脑上运行或者二次开发

quartz数据库存储: 页面版可管理定时任务(CRUD)


11. 启动项目测试

查询后端控制台情况 

 

现在是没有任务的所有控制台是空的 现在我们去前端页面增加数据 

增加成功 我们查看后端控制台情况是否有任务在进行 

增加时所涉及到的cron表达式有小伙伴不明白的请访问下方小编的博客有讲解 

 Quartz【基本使用】_JoneClassMate的博客-CSDN博客

 

ok 现在可以看到我们刚刚所加的任务已经在运行了 

可修改任务参数 比如现在是张三正在女厕所努力的打扫卫生 我们可以修改为李四在男厕所努力的打扫卫生 

 

查看后端控制台是否修改任务参数成功

 

 ok 修改成功 我们可在前端关闭/删除任务 

 

 删除后我们就没有任务了 我们可在后端控制台查看是否控制台已经没有任务在运行了

 

ok 现在已经没有任务在运行了  

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值