这主要分享我的代码案例:
pom依赖:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.5</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.xujie</groupId>
<artifactId>quartz_01</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>quartz_01</name>
<description>quartz_01</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<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>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
properties:
#
#============================================================================
# Configure Main Scheduler Properties \u8C03\u5EA6\u5668\u5C5E\u6027
#============================================================================
org.quartz.scheduler.instanceName:DefaultQuartzScheduler
org.quartz.scheduler.instanceId=AUTO
org.quartz.scheduler.rmi.export:false
org.quartz.scheduler.rmi.proxy:false
org.quartz.scheduler.wrapJobExecutionInUserTransaction:false
org.quartz.threadPool.class:org.quartz.simpl.SimpleThreadPool
org.quartz.threadPool.threadCount=10
org.quartz.threadPool.threadPriority:5
org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread:true
org.quartz.jobStore.misfireThreshold:60000
#============================================================================
# Configure JobStore
#============================================================================
#\u5B58\u50A8\u65B9\u5F0F\u4F7F\u7528JobStoreTX,\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.xujie.quartz_01.util.DruidConnectionProvider
org.quartz.dataSource.qzDS.driver:com.mysql.cj.jdbc.Driver
org.quartz.dataSource.qzDS.URL:jdbc:mysql://127.0.0.1:3306/mysql01?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
conf:
package com.xujie.quartz_01.conf;
import com.xujie.quartz_01.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();
}
}
job:
package com.xujie.quartz_01.job;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
/**
* @author 许缘
* @company xxx公司
* @create 2022-11-09 18:52
*/
@Slf4j
public class MyJob implements Job {
@Override
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
Object name = jobExecutionContext.getJobDetail().getJobDataMap().get("name");
Object loc = jobExecutionContext.getJobDetail().getJobDataMap().get("loc");
log.warn(name+"打扫"+loc);
}
}
pojo:
ScheduleTrigger :
package com.xujie.quartz_01.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;
}
ScheduleTriggerData :
package com.xujie.quartz_01.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:
ScheduleTriggerDataMapper:
package com.xujie.quartz_01.mapper;
import com.xujie.quartz_01.pojo.ScheduleTriggerData;
import org.springframework.stereotype.Repository;
import tk.mybatis.mapper.common.Mapper;
/**
* @author 许缘
* @company xxx公司
* @create 2022-11-10 9:42
*/
@Repository
public interface ScheduleTriggerDataMapper extends Mapper<ScheduleTriggerData> {
}
ScheduleTriggerMapper :
package com.xujie.quartz_01.mapper;
import com.xujie.quartz_01.pojo.ScheduleTrigger;
import org.springframework.stereotype.Repository;
import tk.mybatis.mapper.common.Mapper;
/**
* @author 许缘
* @company xxx公司
* @create 2022-11-10 9:41
*/
@Repository
public interface ScheduleTriggerMapper extends Mapper<ScheduleTrigger> {
}
serviceimpl:
因为service接口没什么就不写啦!直接上实现类
ScheduleTriggerDataServiceImpl :
package com.xujie.quartz_01.service;
import com.xujie.quartz_01.mapper.ScheduleTriggerDataMapper;
import com.xujie.quartz_01.pojo.ScheduleTriggerData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;
import java.util.List;
/**
* @author 许缘
* @company xxx公司
* @create 2022-11-10 10:02
*/
@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);
}
@Override
public int insert(ScheduleTriggerData scheduleTriggerData) {
return mapper.insert(scheduleTriggerData);
}
@Override
public int delete(Long triggerId) {
Example example = new Example(ScheduleTriggerData.class);
example.createCriteria().andEqualTo("triggerId",triggerId);
return mapper.deleteByExample(example);
}
@Override
public int update(ScheduleTriggerData scheduleTriggerData) {
return mapper.updateByPrimaryKey(scheduleTriggerData);
}
}
ScheduleTriggerServiceImpl :
package com.xujie.quartz_01.service;
import com.xujie.quartz_01.mapper.ScheduleTriggerMapper;
import com.xujie.quartz_01.pojo.ScheduleTrigger;
import com.xujie.quartz_01.pojo.ScheduleTriggerData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;
import java.util.List;
/**
* @author 许缘
* @company xxx公司
* @create 2022-11-10 9:52
*/
@Service
public class ScheduleTriggerServiceImpl implements ScheduleTriggerService {
@Autowired
private ScheduleTriggerMapper mapper;
public ScheduleTriggerServiceImpl(ScheduleTriggerMapper mapper) {
this.mapper = mapper;
}
@Override
public List<ScheduleTrigger> find() {
return mapper.selectAll();
}
@Override
public int insert(ScheduleTrigger scheduleTrigger) {
return mapper.insert(scheduleTrigger);
}
@Override
public int delete(Long id) {
Example example = new Example(ScheduleTriggerData.class);
example.createCriteria().andEqualTo("id",id);
return mapper.deleteByExample(example);
}
@Override
public ScheduleTrigger findById(Long id) {
Example example = new Example(ScheduleTriggerData.class);
example.createCriteria().andEqualTo("id",id);
return mapper.selectOneByExample(example);
}
}
util:
DruidConnectionProvider :
package com.xujie.quartz_01.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);
}
}
}
MyJobFactory :
package com.xujie.quartz_01.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
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);
}
}
controller:
QuartzController :
package com.xujie.quartz_01.controller;
import com.xujie.quartz_01.pojo.ScheduleTrigger;
import com.xujie.quartz_01.pojo.ScheduleTriggerData;
import com.xujie.quartz_01.service.ScheduleTriggerDataService;
import com.xujie.quartz_01.service.ScheduleTriggerService;
import lombok.SneakyThrows;
import org.quartz.JobKey;
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;
import java.util.List;
/**
* @author hgh
*/
@Controller
public class QuartzController {
private final ScheduleTriggerService triggerService;
private final ScheduleTriggerDataService dataService;
private final 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:/";
}
@GetMapping("/delete")
@SneakyThrows
public String delete(Long triggerId) {
ScheduleTrigger trigger = triggerService.findById(triggerId);
dataService.delete(triggerId);
triggerService.delete(triggerId);
scheduler.deleteJob(JobKey.jobKey(trigger.getJobName(), trigger.getJobGroup()));
return "redirect:/";
}
@PostMapping("/update")
@SneakyThrows
public String update(Long triggerId,String name,String loc,HttpServletRequest request) {
//根据triggerId得到data的数据集合,拿到对应的数据进行修改
ScheduleTrigger trigger = triggerService.findById(triggerId);
scheduler.deleteJob(JobKey.jobKey(trigger.getJobName(), trigger.getJobGroup()));
dataService.find(triggerId).forEach(t->{
if("name".equals(t.getName())){//name值
t.setValue(name);
dataService.update(t);
}else if("loc".equals(t.getName())){//loc值
t.setValue(loc);
dataService.update(t);
}
});
return "redirect:/";
}
}
注:因为我们写了QuartzTask,所以controller中我们修改自己的数据库的数据时,并没有对quartz的数据库修改,而是直接删除掉了quartz中的任务
QuartzTask :
这里会自己去检查任务,并为我们创建任务,所以不需要去管quartz的数据库。
package com.xujie.quartz_01.util;
import com.xujie.quartz_01.job.MyJob;
import com.xujie.quartz_01.pojo.ScheduleTrigger;
import com.xujie.quartz_01.pojo.ScheduleTriggerData;
import com.xujie.quartz_01.service.ScheduleTriggerDataService;
import com.xujie.quartz_01.service.ScheduleTriggerService;
import lombok.SneakyThrows;
import org.quartz.*;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.Date;
import static org.quartz.JobBuilder.newJob;
/**
* @author 许缘
* @company xxx公司
* @create 2022-11-10 10:15
*/
@Component
public class QuartzTask {
private ScheduleTriggerDataService dataService;
private ScheduleTriggerService triggerService;
private Scheduler scheduler;
public QuartzTask(ScheduleTriggerDataService dataService, ScheduleTriggerService triggerService,Scheduler scheduler) {
this.dataService = dataService;
this.triggerService = triggerService;
this.scheduler = scheduler;
}
@SneakyThrows
@Scheduled(cron = "0/10 * * * * ?")
public void register() throws SchedulerException {
//去数据库看看我的那两张表有没有变化
//查询数据库中的所有任务
for (ScheduleTrigger trigger : triggerService.find()) {
//判断这个任务是否已经被quartz管理了
//拿到这个任务的名字和分组
String jobName = trigger.getJobName();
String jobGroup = trigger.getJobGroup();
String jobDescription = trigger.getJobDescription();
String triggerDescription = trigger.getTriggerDescription();
String cron = trigger.getCron(); //生成一个key,去调度器中拿对应的元素
CronTrigger trigger1 =(CronTrigger) scheduler.getTrigger(TriggerKey.triggerKey(jobName, jobGroup));
if(trigger1 == null){//在我的表里面有 但是quartz没有管理他
//禁用
if("0".equals(trigger.getStatus())){
continue;
}
//新建(将任务放到Quartz里面)
JobDetail jobDetail = newJob((Class<? extends Job>) Class.forName(jobName))
.withDescription(jobDescription) //描述
.withIdentity(jobName, jobGroup)//任务id
.build();//构建
for (ScheduleTriggerData data : dataService.find(trigger.getId())) {
//将任务数据放到任务中
jobDetail.getJobDataMap().put(data.getName(),data.getValue());
}
//4.创建触发器
trigger1 = TriggerBuilder.newTrigger()
.withDescription(triggerDescription)
.withIdentity(jobName, jobGroup)
.withSchedule(CronScheduleBuilder.cronSchedule(cron))
.build();
//分配给调度器
scheduler.scheduleJob(jobDetail,trigger1);
continue;
}
//任务已经在quartz中有了
if("0".equals(trigger.getStatus())){
//在quartz中删除调那个任务
scheduler.deleteJob(JobKey.jobKey(jobName,jobGroup)); //触发器
continue;
}
//任务存在 而且不是禁用状态
//判断是否被修改了
if(!trigger1.getCronExpression().equals(cron)){
//新建(将任务放到Quartz里面)
JobDetail jobDetail = newJob((Class<? extends Job>) Class.forName(jobName))
.withDescription(jobDescription) //描述
.withIdentity(jobName, jobGroup)//任务id
.build();//构建
for (ScheduleTriggerData data : dataService.find(trigger.getId())) {
//将任务数据放到任务中
jobDetail.getJobDataMap().put(data.getName(),data.getValue());
}
//4.创建触发器
trigger1 = TriggerBuilder.newTrigger()
.withDescription(triggerDescription)
.withIdentity(jobName, jobGroup)
.withSchedule(CronScheduleBuilder.cronSchedule(cron))
.build();
//让调度器更换触发器
scheduler.rescheduleJob(TriggerKey.triggerKey(jobName, jobGroup),trigger1);
}
}
}
}
前端页面:
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-primary" data-toggle="modal" data-target="#staticBackdrop" onclick="updateId('${trigger.id}')">修改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.xujie.quartz_01.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>
<div class="modal fade" id="staticBackdrop" data-backdrop="static" data-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="staticBackdropLabel">修改定时任务h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×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="recipient-name" class="col-form-label">name:label>
<input type="text" class="form-control" id="" name="name">
div>
<div class="form-group">
<label for="message-text" class="col-form-label">loc:label>
<textarea class="form-control" id="loc" name="loc">textarea>
div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Closebutton>
<button type="submit" class="btn btn-primary">Understoodbutton>
div>
form>
div>
div>
div>
div>
<script>
function updateId(id){
$("#triggerId").val(id);
};
let node_text =
`
`;
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>
quatrz的mysql数据库:
#
# Quartz seems to work best with the driver mm.mysql-2.0.7-bin.jar
#
# PLEASE consider using mysql with innodb tables to avoid locking issues
#
# In your Quartz properties file, you'll need to set
# org.quartz.jobStore.driverDelegateClass = org.quartz.impl.jdbcjobstore.StdJDBCDelegate
#
DROP TABLE IF EXISTS QRTZ_FIRED_TRIGGERS;
DROP TABLE IF EXISTS QRTZ_PAUSED_TRIGGER_GRPS;
DROP TABLE IF EXISTS QRTZ_SCHEDULER_STATE;
DROP TABLE IF EXISTS QRTZ_LOCKS;
DROP TABLE IF EXISTS QRTZ_SIMPLE_TRIGGERS;
DROP TABLE IF EXISTS QRTZ_SIMPROP_TRIGGERS;
DROP TABLE IF EXISTS QRTZ_CRON_TRIGGERS;
DROP TABLE IF EXISTS QRTZ_BLOB_TRIGGERS;
DROP TABLE IF EXISTS QRTZ_TRIGGERS;
DROP TABLE IF EXISTS QRTZ_JOB_DETAILS;
DROP TABLE IF EXISTS QRTZ_CALENDARS;
CREATE TABLE QRTZ_JOB_DETAILS
(
SCHED_NAME VARCHAR(120) NOT NULL,
JOB_NAME VARCHAR(200) NOT NULL,
JOB_GROUP VARCHAR(200) NOT NULL,
DESCRIPTION VARCHAR(250) NULL,
JOB_CLASS_NAME VARCHAR(250) NOT NULL,
IS_DURABLE VARCHAR(1) NOT NULL,
IS_NONCONCURRENT VARCHAR(1) NOT NULL,
IS_UPDATE_DATA VARCHAR(1) NOT NULL,
REQUESTS_RECOVERY VARCHAR(1) NOT NULL,
JOB_DATA BLOB NULL,
PRIMARY KEY (SCHED_NAME,JOB_NAME,JOB_GROUP)
);
CREATE TABLE QRTZ_TRIGGERS
(
SCHED_NAME VARCHAR(120) NOT NULL,
TRIGGER_NAME VARCHAR(200) NOT NULL,
TRIGGER_GROUP VARCHAR(200) NOT NULL,
JOB_NAME VARCHAR(200) NOT NULL,
JOB_GROUP VARCHAR(200) NOT NULL,
DESCRIPTION VARCHAR(250) NULL,
NEXT_FIRE_TIME BIGINT(13) NULL,
PREV_FIRE_TIME BIGINT(13) NULL,
PRIORITY INTEGER NULL,
TRIGGER_STATE VARCHAR(16) NOT NULL,
TRIGGER_TYPE VARCHAR(8) NOT NULL,
START_TIME BIGINT(13) NOT NULL,
END_TIME BIGINT(13) NULL,
CALENDAR_NAME VARCHAR(200) NULL,
MISFIRE_INSTR SMALLINT(2) NULL,
JOB_DATA BLOB NULL,
PRIMARY KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP),
FOREIGN KEY (SCHED_NAME,JOB_NAME,JOB_GROUP)
REFERENCES QRTZ_JOB_DETAILS(SCHED_NAME,JOB_NAME,JOB_GROUP)
);
CREATE TABLE QRTZ_SIMPLE_TRIGGERS
(
SCHED_NAME VARCHAR(120) NOT NULL,
TRIGGER_NAME VARCHAR(200) NOT NULL,
TRIGGER_GROUP VARCHAR(200) NOT NULL,
REPEAT_COUNT BIGINT(7) NOT NULL,
REPEAT_INTERVAL BIGINT(12) NOT NULL,
TIMES_TRIGGERED BIGINT(10) NOT NULL,
PRIMARY KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP),
FOREIGN KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP)
REFERENCES QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP)
);
CREATE TABLE QRTZ_CRON_TRIGGERS
(
SCHED_NAME VARCHAR(120) NOT NULL,
TRIGGER_NAME VARCHAR(200) NOT NULL,
TRIGGER_GROUP VARCHAR(200) NOT NULL,
CRON_EXPRESSION VARCHAR(200) NOT NULL,
TIME_ZONE_ID VARCHAR(80),
PRIMARY KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP),
FOREIGN KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP)
REFERENCES QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP)
);
CREATE TABLE QRTZ_SIMPROP_TRIGGERS
(
SCHED_NAME VARCHAR(120) NOT NULL,
TRIGGER_NAME VARCHAR(200) NOT NULL,
TRIGGER_GROUP VARCHAR(200) NOT NULL,
STR_PROP_1 VARCHAR(512) NULL,
STR_PROP_2 VARCHAR(512) NULL,
STR_PROP_3 VARCHAR(512) NULL,
INT_PROP_1 INT NULL,
INT_PROP_2 INT NULL,
LONG_PROP_1 BIGINT NULL,
LONG_PROP_2 BIGINT NULL,
DEC_PROP_1 NUMERIC(13,4) NULL,
DEC_PROP_2 NUMERIC(13,4) NULL,
BOOL_PROP_1 VARCHAR(1) NULL,
BOOL_PROP_2 VARCHAR(1) NULL,
PRIMARY KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP),
FOREIGN KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP)
REFERENCES QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP)
);
CREATE TABLE QRTZ_BLOB_TRIGGERS
(
SCHED_NAME VARCHAR(120) NOT NULL,
TRIGGER_NAME VARCHAR(200) NOT NULL,
TRIGGER_GROUP VARCHAR(200) NOT NULL,
BLOB_DATA BLOB NULL,
PRIMARY KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP),
FOREIGN KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP)
REFERENCES QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP)
);
CREATE TABLE QRTZ_CALENDARS
(
SCHED_NAME VARCHAR(120) NOT NULL,
CALENDAR_NAME VARCHAR(200) NOT NULL,
CALENDAR BLOB NOT NULL,
PRIMARY KEY (SCHED_NAME,CALENDAR_NAME)
);
CREATE TABLE QRTZ_PAUSED_TRIGGER_GRPS
(
SCHED_NAME VARCHAR(120) NOT NULL,
TRIGGER_GROUP VARCHAR(200) NOT NULL,
PRIMARY KEY (SCHED_NAME,TRIGGER_GROUP)
);
CREATE TABLE QRTZ_FIRED_TRIGGERS
(
SCHED_NAME VARCHAR(120) NOT NULL,
ENTRY_ID VARCHAR(95) NOT NULL,
TRIGGER_NAME VARCHAR(200) NOT NULL,
TRIGGER_GROUP VARCHAR(200) NOT NULL,
INSTANCE_NAME VARCHAR(200) NOT NULL,
FIRED_TIME BIGINT(13) NOT NULL,
SCHED_TIME BIGINT(13) NOT NULL,
PRIORITY INTEGER NOT NULL,
STATE VARCHAR(16) NOT NULL,
JOB_NAME VARCHAR(200) NULL,
JOB_GROUP VARCHAR(200) NULL,
IS_NONCONCURRENT VARCHAR(1) NULL,
REQUESTS_RECOVERY VARCHAR(1) NULL,
PRIMARY KEY (SCHED_NAME,ENTRY_ID)
);
CREATE TABLE QRTZ_SCHEDULER_STATE
(
SCHED_NAME VARCHAR(120) NOT NULL,
INSTANCE_NAME VARCHAR(200) NOT NULL,
LAST_CHECKIN_TIME BIGINT(13) NOT NULL,
CHECKIN_INTERVAL BIGINT(13) NOT NULL,
PRIMARY KEY (SCHED_NAME,INSTANCE_NAME)
);
CREATE TABLE QRTZ_LOCKS
(
SCHED_NAME VARCHAR(120) NOT NULL,
LOCK_NAME VARCHAR(40) NOT NULL,
PRIMARY KEY (SCHED_NAME,LOCK_NAME)
);
commit;
我们自己写的数据库:
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)
);
效果展示:
OK,今天就到这里了。