目录
1. 导入pom依赖
2. resources模块
3. pojo模块
4. mapper模块
5. service模块
6. job模块
7. controller模块
8. config模块
9. utils模块
10. springboot启动类配置
11. 启动项目测试
org.springframework.boot
spring-boot-starter-quartz
org.springframework.boot
spring-boot-starter-freemarker
org.springframework.boot
spring-boot-starter-test
test
org.projectlombok
lombok
com.alibaba
druid-spring-boot-starter
1.2.8
org.springframework.boot
spring-boot-starter-web
tk.mybatis
mapper-spring-boot-starter
2.0.2
javax.persistence
persistence-api
1.0
compile
mysql
mysql-connector-java
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
定时任务情况
表达式
名字(执行类名)
分组
描述
触发器描述
状态
操作
<#list triggers as trigger>
${trigger.cron!""}
${trigger.jobName!""}
${trigger.jobGroup!""}
${trigger.jobDescription!""}
${trigger.triggerDescription!""}
${(trigger.status=='0')?string("已禁用","启用中")}
关闭
修改
#list>
新增定时任务
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.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{
}
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 {
}
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 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 find(Long triggerId);
int insert(ScheduleTriggerData scheduleTriggerData);
int delete(Long trigger);
int update(ScheduleTriggerData scheduleTriggerData);
}
5.3 impl模块实现类
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 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);
}
}
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 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);
}
}
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") + "努力的打扫卫生");
}
}
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 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 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:/";
}
}
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.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);
}
}
}
}
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)
查询后端控制台情况
现在是没有任务的所有控制台是空的 现在我们去前端页面增加数据
增加成功 我们查看后端控制台情况是否有任务在进行
增加时所涉及到的cron表达式有小伙伴不明白的请访问下方小编的博客有讲解
Quartz【基本使用】_JoneClassMate的博客-CSDN博客
ok 现在可以看到我们刚刚所加的任务已经在运行了
可修改任务参数 比如现在是张三正在女厕所努力的打扫卫生 我们可以修改为李四在男厕所努力的打扫卫生
查看后端控制台是否修改任务参数成功
ok 修改成功 我们可在前端关闭/删除任务
删除后我们就没有任务了 我们可在后端控制台查看是否控制台已经没有任务在运行了
ok 现在已经没有任务在运行了