导入quartz所需要的内置表
quartz 如果要将定时任务的数据持久化到数据库就需要导入quartz的内置表
进入quartz的官网http://www.quartz-scheduler.org/,点击Downloads,下载后在目录\docs\dbTables下有常用数据库创建quartz表的脚本,例如:“tables_mysql.sql
,你是啥数据库就导入啥对应的 脚本就好了
ps: table_mysql_innodb.sql 这个是针对 mysql中innodb 这个引擎的,如果你使用的是这个引擎就导入这个吧
自定义的业务表
-- 注意:job_name存放的任务类的全路径,在quartz中通过jobName和jobGroup来确定trigger的唯一性,所以这两列为联合唯一索引
create table t_schedule_trigger
(
id int primary key auto_increment, -- ID
cron varchar(200) not null, -- 时间表达式
status char(1) not null, -- 使用状态 0:禁用 1:启用
job_name varchar(200) not null, -- 任务名称
job_group varchar(200) not null, -- 任务分组
unique index(job_name,job_group)
);
-- 额外添加到任务中的参数
create table t_schedule_trigger_param
(
param_id int primary key auto_increment, -- ID
name varchar(200) not null, -- 参数名
value varchar(512), -- 参数值
schedule_trigger_id int not null, -- 外键:引用t_schedule_trigger(id)
foreign key(schedule_trigger_id) references t_schedule_trigger(id)
);
案例中需要观察表数据变化的表
-- 自定义的业务表
SELECT * FROM t_schedule_trigger;
SELECT * FROM t_schedule_trigger_param;
-- quartz调度框架自带的表
SELECT * FROM qrtz_scheduler_state;
SELECT * FROM qrtz_cron_triggers;
SELECT * FROM qrtz_simple_triggers
SELECT * FROM qrtz_triggers;
SELECT * FROM qrtz_job_details;
创建springboot项目
这是此处项目所要用到的启动器
maven中还需添加:
<dependency>
<groupId>org.quartz-schedulergroupId>
<artifactId>quartz-jobsartifactId>
<version>2.2.1version>
dependency>
<dependency>
<groupId>com.github.pagehelpergroupId>
<artifactId>pagehelper-spring-boot-starterartifactId>
<version>1.2.3version>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druid-spring-boot-starterartifactId>
<version>1.1.10version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-aspectsartifactId>
dependency>
pom.xml所有代码:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0modelVersion>
<parent>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-parentartifactId>
<version>2.2.1.RELEASEversion>
<relativePath/>
parent>
<groupId>com.cpcgroupId>
<artifactId>demoartifactId>
<version>0.0.1-SNAPSHOTversion>
<name>demoname>
<description>Demo project for Spring Bootdescription>
<properties>
<java.version>1.8java.version>
properties>
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-data-jdbcartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-quartzartifactId>
dependency>
<dependency>
<groupId>org.quartz-schedulergroupId>
<artifactId>quartz-jobsartifactId>
<version>2.2.1version>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-thymeleafartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>org.mybatis.spring.bootgroupId>
<artifactId>mybatis-spring-boot-starterartifactId>
<version>2.1.1version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<scope>runtimescope>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<optional>trueoptional>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
<scope>testscope>
<exclusions>
<exclusion>
<groupId>org.junit.vintagegroupId>
<artifactId>junit-vintage-engineartifactId>
exclusion>
exclusions>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druid-spring-boot-starterartifactId>
<version>1.1.10version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-aspectsartifactId>
dependency>
<dependency>
<groupId>com.github.pagehelpergroupId>
<artifactId>pagehelper-spring-boot-starterartifactId>
<version>1.2.3version>
dependency>
dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-maven-pluginartifactId>
plugin>
plugins>
build>
project>
修改quartz数据源为 Druid
说明:
quartz 需要用到数据库连接池,Quartz 2.0 以前默认使用 DBCP。Quartz 2.0 以后 默认C3P0(包含2.0)。下面我们要将数据源修改为 Druid
基本步骤:
(1)导入依赖(上面已经导入了)
(2)导入DruidConnectionProvider.java
(3)修改quartz.properties配置
导入DruidConnectionProvider.java
package com.cpc.util;
import com.alibaba.druid.pool.DruidDataSource;
import org.quartz.SchedulerException;
import org.quartz.utils.ConnectionProvider;
import java.sql.Connection;
import java.sql.SQLException;
/*
#============================================================================
# JDBC
#============================================================================
org.quartz.jobStore.driverDelegateClass:org.quartz.impl.jdbcjobstore.StdJDBCDelegate
org.quartz.jobStore.useProperties:false
org.quartz.jobStore.dataSource:qzDS
#org.quartz.dataSource.qzDS.connectionProvider.class:org.quartz.utils.PoolingConnectionProvider
org.quartz.dataSource.qzDS.connectionProvider.class:com.javaxl.q03.quartz.DruidConnectionProvider
org.quartz.dataSource.qzDS.driver:com.mysql.jdbc.Driver
org.quartz.dataSource.qzDS.URL:jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=UTF-8
org.quartz.dataSource.qzDS.user:root
org.quartz.dataSource.qzDS.password:root
org.quartz.dataSource.qzDS.maxConnections:30
org.quartz.dataSource.qzDS.validationQuery: select 0
*/
/**
* [Druid连接池的Quartz扩展类]
*
* @ProjectName: []
* @Author: [xuguang]
* @CreateDate: [2015/11/10 17:58]
* @Update: [说明本次修改内容] BY[xuguang][2015/11/10]
* @Version: [v1.0]
*/
public class DruidConnectionProvider implements ConnectionProvider {
/*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*
* 常量配置,与quartz.properties文件的key保持一致(去掉前缀),同时提供set方法,Quartz框架自动注入值。
*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/
//JDBC驱动
public String driver;
//JDBC连接串
public String URL;
//数据库用户名
public String user;
//数据库用户密码
public String password;
//数据库最大连接数
public int maxConnection;
//数据库SQL查询每次连接返回执行到连接池,以确保它仍然是有效的。
public String validationQuery;
private boolean validateOnCheckout;
private int idleConnectionValidationSeconds;
public String maxCachedStatementsPerConnection;
private String discardIdleConnectionsSeconds;
public static final int DEFAULT_DB_MAX_CONNECTIONS = 10;
public static final int DEFAULT_DB_MAX_CACHED_STATEMENTS_PER_CONNECTION = 120;
//Druid连接池
private DruidDataSource datasource;
/*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*
* 接口实现
*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/
public Connection getConnection() throws SQLException {
return datasource.getConnection();
}
public void shutdown() throws SQLException {
datasource.close();
}
public void initialize() throws SQLException{
if (this.URL == null) {
throw new SQLException("DBPool could not be created: DB URL cannot be null");
}
if (this.driver == null) {
throw new SQLException("DBPool driver could not be created: DB driver class name cannot be null!");
}
if (this.maxConnection < 0) {
throw new SQLException("DBPool maxConnectins could not be created: Max connections must be greater than zero!");
}
datasource = new DruidDataSource();
try{
datasource.setDriverClassName(this.driver);
} catch (Exception e) {
try {
throw new SchedulerException("Problem setting driver class name on datasource: " + e.getMessage(), e);
} catch (SchedulerException e1) {
}
}
datasource.setUrl(this.URL);
datasource.setUsername(this.user);
datasource.setPassword(this.password);
datasource.setMaxActive(this.maxConnection);
datasource.setMinIdle(1);
datasource.setMaxWait(0);
datasource.setMaxPoolPreparedStatementPerConnectionSize(this.DEFAULT_DB_MAX_CACHED_STATEMENTS_PER_CONNECTION);
if (this.validationQuery != null) {
datasource.setValidationQuery(this.validationQuery);
if(!this.validateOnCheckout)
datasource.setTestOnReturn(true);
else
datasource.setTestOnBorrow(true);
datasource.setValidationQueryTimeout(this.idleConnectionValidationSeconds);
}
}
/*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*
* 提供get set方法
*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/
public String getDriver() {
return driver;
}
public void setDriver(String driver) {
this.driver = driver;
}
public String getURL() {
return URL;
}
public void setURL(String URL) {
this.URL = URL;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getMaxConnection() {
return maxConnection;
}
public void setMaxConnection(int maxConnection) {
this.maxConnection = maxConnection;
}
public String getValidationQuery() {
return validationQuery;
}
public void setValidationQuery(String validationQuery) {
this.validationQuery = validationQuery;
}
public boolean isValidateOnCheckout() {
return validateOnCheckout;
}
public void setValidateOnCheckout(boolean validateOnCheckout) {
this.validateOnCheckout = validateOnCheckout;
}
public int getIdleConnectionValidationSeconds() {
return idleConnectionValidationSeconds;
}
public void setIdleConnectionValidationSeconds(int idleConnectionValidationSeconds) {
this.idleConnectionValidationSeconds = idleConnectionValidationSeconds;
}
public DruidDataSource getDatasource() {
return datasource;
}
public void setDatasource(DruidDataSource datasource) {
this.datasource = datasource;
}
}
在项目中添加quartz.properties文件(这样就不会加载自带的properties文件),此文件的内容主要分为:scheduler,ThreadPool,JobStore,plugin,Datasources等部分,覆盖properties文件的目的是覆盖默认的数据源,更换为druid的数据配置
#
#============================================================================
# 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.cpc.util.DruidConnectionProvider
org.quartz.dataSource.qzDS.driver: com.mysql.jdbc.Driver
org.quartz.dataSource.qzDS.URL: jdbc:mysql://localhost:3306/cpc?useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
org.quartz.dataSource.qzDS.user: root
org.quartz.dataSource.qzDS.password: root
org.quartz.dataSource.qzDS.maxConnection: 10
导入 MyJobFactory,让job类实现bean主任的功能
package com.cpc.config;
import lombok.extern.slf4j.Slf4j;
import org.quartz.spi.TriggerFiredBundle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.scheduling.quartz.AdaptableJobFactory;
import org.springframework.stereotype.Component;
@Component
@Slf4j
public class MyJobFactory extends AdaptableJobFactory {
//这个由Spring自动注入
@Autowired
private AutowireCapableBeanFactory autowireCapableBeanFactory;
//重写Job任务对象的创建实例方法
@Override
protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception {
Object jobInstance = super.createJobInstance(bundle);
//通过以下方式,解决Job任务无法使用Spring中的Bean问题
autowireCapableBeanFactory.autowireBean(jobInstance);
//这个时候 jobInstance 已经交给spring管理
return jobInstance;
}
}
QuartzConfiguration.java(quartz调度框架与spring框架整合的配置类,主要是要将org.quartz.Scheduler交给spring进行管理)
package com.cpc.config;
import org.quartz.Scheduler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import java.io.IOException;
import java.util.Properties;
@Configuration
public class QuartzConfiguration {
@Autowired
private MyJobFactory myJobFactory;
//创建调度器工厂
@Bean
public SchedulerFactoryBean schedulerFactoryBean(){
//1.创建SchedulerFactoryBean
//2.加载自定义的quartz.properties配置文件
//3.设置MyJobFactory
SchedulerFactoryBean factoryBean=new SchedulerFactoryBean();
try {
factoryBean.setQuartzProperties(quartzProperties());
factoryBean.setJobFactory(myJobFactory);
return factoryBean;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Bean
public Properties quartzProperties() throws IOException {
PropertiesFactoryBean propertiesFactoryBean=new PropertiesFactoryBean();
propertiesFactoryBean.setLocation(new ClassPathResource("/quartz.properties"));
propertiesFactoryBean.afterPropertiesSet();
return propertiesFactoryBean.getObject();
}
@Bean(name="scheduler")
public Scheduler scheduler(){
return schedulerFactoryBean().getScheduler();
}
}
application.yml
server:
servlet:
context-path: /
port: 80
spring:
datasource:
#1.JDBC
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/cpc?useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
username: root
password: root
druid:
#2.连接池配置
#初始化连接池的连接数量 大小,最小,最大
initial-size: 5
min-idle: 5
max-active: 20
#配置获取连接等待超时的时间
max-wait: 60000
#配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
time-between-eviction-runs-millis: 60000
# 配置一个连接在池中最小生存的时间,单位是毫秒
min-evictable-idle-time-millis: 30000
validation-query: SELECT 1 FROM DUAL
test-while-idle: true
test-on-borrow: true
test-on-return: false
# 是否缓存preparedStatement,也就是PSCache 官方建议MySQL下建议关闭 个人建议如果想用SQL防火墙 建议打开
pool-prepared-statements: true
max-pool-prepared-statement-per-connection-size: 20
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
filter:
stat:
merge-sql: true
slow-sql-millis: 5000
#3.基础监控配置
web-stat-filter:
enabled: true
url-pattern: /*
#设置不统计哪些URL
exclusions: "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*"
session-stat-enable: true
session-stat-max-count: 100
stat-view-servlet:
enabled: true
url-pattern: /druid/*
reset-enable: true
#设置监控页面的登录名和密码
login-username: admin
login-password: admin
allow: 127.0.0.1
#deny: 192.168.1.100
thymeleaf:
cache: false
encoding: utf-8
#显示日志
logging:
level:
com.javaxl.quartz02.mapper: debug
pagehelper:
helperDialect: mysql
reasonable: true
supportMethodsArguments: true
params: count=countSql
mybatis:
mapper-locations: classpath:mappings/*.xml
启动类:
package com.cpc;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@MapperScan("com.cpc.dao")
@EnableTransactionManagement
@EnableScheduling
@SpringBootApplication
public class CpcApplication {
public static void main(String[] args) {
SpringApplication.run(CpcApplication.class, args);
}
}
jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/cpc?useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
jdbc.username=root
jdbc.password=root
jdbc.initialSize=10
jdbc.maxTotal=100
jdbc.maxIdle=50
jdbc.minIdle=10
jdbc.maxWaitMillis=-1
下面是我使用代码生成工具生成的简单对 t_schedule_trigger
和 t_schedule_trigger_param
表的 curd
在生成的curd上在加了点方法:
TScheduleTriggerMapper.java
java:
/**
* 查询触发器中包含的所有任务
* @return
*/
List<TScheduleTrigger> queryScheduleTriggerLst();
xml:
<select id="queryScheduleTriggerLst" resultMap="TScheduleTriggerMap">
select id, cron, status, job_name, job_group
from t_schedule_trigger
</select>
注:此处省略service 代码
TScheduleTriggerParamMapper.java
java:
/**
* 查询出当前任务类对应所需的参数
* @param triggerId
* @return
*/
List<TScheduleTriggerParam> queryScheduleParamLst(Integer triggerId);
xml:
<select id="queryScheduleParamLst" resultMap="TScheduleTriggerParamMap">
select param_id, name, value, schedule_trigger_id from t_schedule_trigger_param where schedule_trigger_id=#{triggerId}
</select>
注:此处省略service 代码
spring自带定时任务作业类SpringTaskByQaurtz .java
import com.cpc.dao.TScheduleTriggerMapper;
import com.cpc.entity.TScheduleTrigger;
import com.cpc.entity.TScheduleTriggerParam;
import com.cpc.service.TScheduleTriggerParamService;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import javax.annotation.Resource;
import java.util.List;
/**
* @Description:
* @Author: cpc
* @Date: 2019-11-16 8:47
* @Version: V1.0
*/
@Component
public class SpringTaskByQaurtz {
@Resource
private TScheduleTriggerMapper tScheduleTriggerDao;
@Resource
private TScheduleTriggerParamService tScheduleTriggerParamService;
@Autowired
private Scheduler scheduler;
//这是每10秒中将调用一次这个方法
@Scheduled(cron = "0/10 * * * * ?")
public void refreshScheduler(){
try {
//这是查找出所有数据库中的定时任务数据
List<TScheduleTrigger> scheduleTriggers =
tScheduleTriggerDao.queryScheduleTriggerLst();
if(null!=scheduleTriggers){
//循环开启定时任务
for (TScheduleTrigger scheduleTrigger : scheduleTriggers) {
String cron = scheduleTrigger.getCron(); //表达式
String jobName = scheduleTrigger.getJobName(); //任务名称
String jobGroup = scheduleTrigger.getJobGroup(); //任务分组
String status = scheduleTrigger.getStatus(); //任务状态
//JobName+JobGroup=Primary Key
//根据jobName和jobGroup生成TriggerKey
TriggerKey triggerKey =
TriggerKey.triggerKey(jobName, jobGroup);
//根据TriggerKey到Scheduler调度器中获取触发器
CronTrigger cronTrigger = (CronTrigger)
scheduler.getTrigger(triggerKey);
if(null==cronTrigger){
//这是还没创建的定时任务 也就是 cronTrigger 为空的清空
if(status.equals("0"))
continue;
System.out.println("创建调度器");
//创建任务详情
JobDetail jobDetail=
JobBuilder.newJob((Class<? extends Job>) Class.forName(jobName))
.withIdentity(jobName,jobGroup)
.build();
//往Job任务中传递参数
JobDataMap jobDataMap = jobDetail.getJobDataMap();
List<TScheduleTriggerParam> params =
tScheduleTriggerParamService.queryScheduleParamLst(scheduleTrigger.getId());
for (TScheduleTriggerParam param : params) {
jobDataMap.put(param.getName(),param.getValue());
}
//创建表达式调度器
CronScheduleBuilder cronSchedule =
CronScheduleBuilder.cronSchedule(cron);
//创建Trigger
cronTrigger=TriggerBuilder.newTrigger()
.withIdentity(jobName,jobGroup)
.withSchedule(cronSchedule)
.build();
//将jobDetail和Trigger注入到scheduler调度器中
scheduler.scheduleJob(jobDetail,cronTrigger);
}else{
//System.out.println("Quartz 调度任务中已存在该任务");
if(status.equals("0")){
//如果禁用就直接将定时任务给关了
JobKey jobKey = JobKey.jobKey(jobName, jobGroup);
scheduler.deleteJob(jobKey);
continue;
}
//调度器中的表达式
String cronExpression =
cronTrigger.getCronExpression();
if(!cron.equals(cronExpression)){
//创建表达式调度器
CronScheduleBuilder cronSchedule =
CronScheduleBuilder.cronSchedule(cron);
//重构
cronTrigger=cronTrigger.getTriggerBuilder()
.withIdentity(triggerKey)
.withSchedule(cronSchedule)
.build();
//刷新调度器
scheduler.rescheduleJob(triggerKey,cronTrigger);
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
数据库表t_schedule_trigger配置
MyJob.java
package com.cpc.job;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.stereotype.Component;
import java.util.Date;
@Component
@Slf4j
public class MyJob implements Job {
@Override
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
System.out.println("MyJob是一个空的任务计划,时间:"+new Date().toLocaleString());
}
}
Spring自带定时任务每10s执行一次,查询自定义触发器表,获取到具体的作业类及任务表达式,quartz的任务为每5s执行一次,所以打印如上
更改数据库调度器表t_schedule_trigger的state状态
应为spring自带的定时任务会没10秒指向一次所有当我们对数据库进行修改的时候到了对应的时间点就刷新了
t_schedule_trigger
t_schedule_trigger_param
MyJobParam
package com.cpc.job;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.springframework.stereotype.Component;
import java.util.Date;
/**
* @Description:
* @Author: cpc
* @Date: 2019-11-15 18:40
* @Version: V1.0
*/
@Component
@Slf4j
public class MyJobParam implements Job {
@Override
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
JobDetail jobDetail =
jobExecutionContext.getJobDetail();
JobDataMap jobDataMap = jobDetail.getJobDataMap();
System.out.println(new Date().toLocaleString()+"-->携带参数个数:"+jobDataMap.size());
}
}
程序执行spring自带的定时任务,每10s执行一次查询,查询t_schedule_trigger表,调度器是需要携带参数的,携带的参数在t_schedule_trigger_param表中,所以一开始调度器启动的时候需要查询t_schedule_trigger_param表数据,最终打印语句如上。
t_schedule_trigger
t_schedule_trigger_param
作业类
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.springframework.stereotype.Component;
import java.util.Date;
/**
* @Description:
* @Author: cpc
* @Date: 2019-11-15 18:49
* @Version: V1.0
*/
@Component
@Slf4j
public class MyJobParam2 implements Job {
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
JobDetail jobDetail =
jobExecutionContext.getJobDetail();
JobDataMap jobDataMap = jobDetail.getJobDataMap();
System.out.println(new Date().toLocaleString()+"-->MyJobParam2参数传递name="+jobDataMap.get("name")+",score="+
jobDataMap.get("score"));
}
}
TScheduleTriggerParamServiceImpl
package com.cpc.service.impl;
import com.cpc.dao.TScheduleTriggerParamMapper;
import com.cpc.entity.TScheduleTriggerParam;
import com.cpc.service.TScheduleTriggerParamService;
import com.cpc.util.Query;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
/**
* (TScheduleTriggerParam)表服务实现类
*
* @author cpc
* @since 2019-11-15 16:47:41
*/
@Service("tScheduleTriggerParamService")
public class TScheduleTriggerParamServiceImpl implements TScheduleTriggerParamService {
@Resource
private TScheduleTriggerParamMapper tScheduleTriggerParamDao;
/**
* 通过ID查询单条数据
*
* @param paramId 主键
* @return 实例对象
*/
@Override
public TScheduleTriggerParam queryById(Integer paramId) {
return this.tScheduleTriggerParamDao.queryById(paramId);
}
/**
* 通过query对象查询
*
* @param query 分页查询对象
* @return 对象列表
*/
@Override
public List<TScheduleTriggerParam> queryPager(Query query) {
return this.tScheduleTriggerParamDao.queryPager(query);
}
@Override
public List<TScheduleTriggerParam> queryScheduleParamLst(Integer triggerId) {
return this.tScheduleTriggerParamDao.queryScheduleParamLst(triggerId);
}
/**
* 新增数据
*
* @param tScheduleTriggerParam 实例对象
* @return 实例对象
*/
@Override
public int insert(TScheduleTriggerParam tScheduleTriggerParam) {
return this.tScheduleTriggerParamDao.insert(tScheduleTriggerParam);
}
/**
* 修改数据
*
* @param tScheduleTriggerParam 实例对象
* @return 实例对象
*/
@Override
public int update(TScheduleTriggerParam tScheduleTriggerParam) {
return this.tScheduleTriggerParamDao.update(tScheduleTriggerParam);
}
/**
* 通过主键删除数据
*
* @param paramId 主键
* @return 是否成功
*/
@Override
public int deleteById(Integer paramId) {
return this.tScheduleTriggerParamDao.deleteById(paramId);
}
@Override
public int deleteByScheduleTriggerId(Integer scheduleTriggerId) {
return this.tScheduleTriggerParamDao.deleteByScheduleTriggerId(scheduleTriggerId);
}
}
TScheduleTriggerController
package com.cpc.controller;
import com.cpc.entity.TScheduleTrigger;
import com.cpc.service.TScheduleTriggerService;
import com.cpc.util.PageUtils;
import com.cpc.util.Query;
import com.cpc.util.R;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import java.util.List;
import java.util.Map;
/**
* (TScheduleTrigger)表控制层
*
* @author cpc
* @since 2019-11-15 16:47:41
*/
@RestController
@RequestMapping("tScheduleTrigger")
public class TScheduleTriggerController {
@Autowired
private TScheduleTriggerService tScheduleTriggerService;
/**
* 分页查询
*
* @param params 请求参数集
* @return 结果集封装对象
*/
@GetMapping("queryPager")
public PageUtils queryPager(@RequestParam Map<String, Object> params) {
Query query = new Query(params);
List<TScheduleTrigger> list = tScheduleTriggerService.queryPager(query);
return new PageUtils(list, query.getTotal());
}
/**
* 新增数据
*
* @param tScheduleTrigger 实例对象
* @return R
*/
@PostMapping("add")
public R add(TScheduleTrigger tScheduleTrigger) {
R r = R.update(tScheduleTriggerService.insert(tScheduleTrigger));
//刷新定时任务
this.tScheduleTriggerService.refreshScheduler();
return r;
}
/**
* 修改数据
*
* @param tScheduleTrigger 实例对象
* @return R
*/
@PostMapping("update")
public R update(TScheduleTrigger tScheduleTrigger) {
R r = R.update(tScheduleTriggerService.update(tScheduleTrigger));
//刷新定时任务
this.tScheduleTriggerService.refreshScheduler();
return r;
}
/**
* 删除数据
*
* @param id 主键
* @return R
*/
@PostMapping("del")
public R del(Integer id) throws SchedulerException {
R r = R.update(tScheduleTriggerService.deleteById(id));
//刷新定时任务
this.tScheduleTriggerService.refreshScheduler();
return r;
}
@RequestMapping("toQuarztManagement")
public ModelAndView toQuarztManagement(){
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("quarztManagement");
return modelAndView;
}
}
MyWebAppConfigurer
package com.cpc.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
/**
* 资源映射路径
*/
@Configuration
public class MyWebAppConfigurer extends WebMvcConfigurationSupport {
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
super.addResourceHandlers(registry);
}
}
导入layui 到static下,当然你也可以去找cdn 这个随便
quarztManagement.html
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" th:href="@{/static/layui/css/layui.css}">
<script type="text/javascript"
th:src="@{/static/layui/layui.js}">script>
<style>
.layui-table-cell .layui-form-checkbox[lay-skin="primary"] {
top: 50%;
transform: translateY(-50%);
}
style>
head>
<body class="childrenBody" style="padding: 10px;">
<div class="layui-form">
<form class="layui-row layui-form" onsubmit="return false">
<div class="layui-inline layui-col-xs3 layui-col-sm3 layui-col-md3">
<label class="layui-form-label" style="width: 80px;">所在组织label>
<div class="layui-input-inline">
<input type="text" id='jobGroupSearch' name="jobGroup" placeholder="请输入流程所在组织" autocomplete="true"
class="layui-input">
div>
div>
<div class="layui-inline layui-col-xs2 layui-col-sm2 layui-col-md2">
<button class="layui-btn" lay-submit lay-filter="search">查询button>
<button class="layui-btn layui-btn-normal" data-type="add">新建button>
div>
form>
div>
<div class="demoTable" style="margin-top: 15px">
<div class=layui-form>
<table class="layui-table" id="quarzTable" lay-filter="quarzTable"
lay-data="{id: 'quarzTable'}">
table>
div>
div>
<script type="text/html" id="quarzTableRowBar">
<a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
script>
<div class="site-text" style="margin: 5%; display: none"
id="quarzFormBox" target="test123">
<form class="layui-form" onsubmit="return false" id="quarzForm"
lay-filter="quarzForm">
<input type="hidden" id="id" name="id"> <input
type="hidden" id="oldName" name="oldName">
<div class="layui-row" style="margin-top: 15px">
<div
class="layui-inline layui-col-xs12 layui-col-sm12 layui-col-md12">
<label class="layui-form-label">所在组织label>
<div class="layui-input-block">
<input type="text" class="layui-input text_add my_clear"
id="jobGroup" name="jobGroup" required lay-verify="required">
div>
div>
div>
<div class="layui-row" style="margin-top: 15px">
<div
class="layui-inline layui-col-xs12 layui-col-sm12 layui-col-md12">
<label class="layui-form-label">cronlabel>
<div class="layui-input-block">
<input type="text" class="layui-input my_clear"
id="cron" name="cron" required
lay-verify="required">
div>
div>
div>
<div class="layui-row" style="margin-top: 15px">
<div
class="layui-inline layui-col-xs12 layui-col-sm12 layui-col-md12">
<label class="layui-form-label">状态label>
<div class="layui-input-block">
<input type="checkbox" name="status" id="status"
lay-skin="switch" lay-filter="status" checked>
div>
div>
div>
<div class="layui-row" style="margin-top: 15px">
<div
class="layui-inline layui-col-xs12 layui-col-sm12 layui-col-md12">
<label class="layui-form-label">job类限定名label>
<div class="layui-input-block">
<input type="text" class="layui-input my_clear"
id="jobName" name="jobName" required
lay-verify="required">
div>
div>
div>
<div class="layui-row" style="margin-top: 60px">
<div
class="layui-inline layui-col-xs12 layui-col-sm12 layui-col-md12"
style="text-align: right">
<button class="layui-btn" lay-submit lay-filter="quarzFormSubmit">提交button>
div>
div>
form>
div>
<script th:src="@{/static/js/quarztManagement.js}">script>
body>
HTML>
quarztManagement.js
var path = 'http://localhost';
//当前调用方法
var methodName = null;
//当前弹出
var index = null;
//当前操作 的 定时任务id
var scheduleTriggerId = null;
// 定时任务管理
layui.use(['table', 'form', 'jquery'],
// , 'from'
function () {
var table = layui.table,
form = layui.form;
// 第一个实例
table.render({
elem : '#quarzTable',
url : path + '/tScheduleTrigger/queryPager',// 数据接口
page : true, // 开启分页
limit: 5,
loading:true,
limits : [ 5, 10, 15 ],
cellMinWidth : 80,
cols : [ [
{
field : 'id',
title : '编号',
sort : true
},{
field : 'jobGroup',
title : '所在组织'
},{
field : 'cron',
title : 'cron'
},{
field : 'status',
title : '状态'
},{
field : 'jobName',
title : 'jobName'
},{
fixed : 'right',
title : '操作',
align : 'center',
toolbar : '#quarzTableRowBar'
}
] ],
id : 'quarzTableReload'
});
// 上方菜单
var $ = layui.$,
active = {
add: function () { // 添加
layer.open({
type: 1,
title: '添加定时任务',
maxmin: true,
shadeClose: true, // 点击遮罩关闭层
area: ['60%', '73%'],
content: $('#quarzFormBox'),
success: function (layero, n) {// 弹出后执行的函数
methodName = 'add';
index = n;
},
cancel:function (index, layero) {
$(".my_clear").val("");
layer.close(index)
}
});
}
}
$('.layui-form .layui-btn').on('click', function () {
var type = $(this).data('type');
active[type] ? active[type].call(this) : '';
});
//监听查询提交事件
form.on('submit(search)', function(event){
var data = event.field;
// 执行重载
table.reload('quarzTableReload', {
page: {
curr: 1 // 重新从第 1 页开始
},
where:data
});
return false;
});
//监听提交 (添加|修改)
form.on('submit(quarzFormSubmit)', function (event) {
var data = event.field;
data.status = document.getElementById('status').checked? 1: 0;
if(methodName == 'add'){ //如果是添加
$.post(path + '/tScheduleTrigger/add',data, function (data) {
if (data.code == 0) {
layer.alert('创建成功', {
icon: 1,
title: '提示'
}, function (i) {
layer.close(i);
layer.close(index);// 关闭弹出层
$(".my_clear").val("");
table.reload('quarzTableReload', {// 重载表格
page: {
curr: 1 // 重新从第 1 页开始
}
})
})
}
})
}else{ //这是修改
$.post(path + '/tScheduleTrigger/update',data, function (data) {
if (data.code == 0) {
layer.alert('修改', {
icon: 1,
title: '提示'
}, function (i) {
layer.close(i);
layer.close(index);// 关闭弹出层
table.reload('quarzTableReload', {// 重载表格
page: {
curr: 1 // 重新从第 1 页开始
}
})
})
}
})
}
return false;
});
// table菜单
table.on('tool(quarzTable)', function (obj) {
var data = obj.data;// 获得当前行数据
var layEvent = obj.event; // 获得 lay-event 对应的值(也可以是表头的event参数对应的值)
var tr = obj.tr; // 获得当前行 tr 的DOM对象
if (layEvent == 'edit') {// 编辑
layer.open({
type: 1,
title: '修改',
maxmin: true,
shadeClose: true, // 点击遮罩关闭层
area: ['60%', '73%'],
content: $('#quarzFormBox'),
success: function (layero, n) {// 弹出后执行的函数
document.getElementById("status").checked = data.status == 1;
form.render(); //重新渲染
$("#id").val(data.id);
$("#cron").val(data.cron);
$("#status").val(data.status);
$("#jobName").val(data.jobName);
$("#jobGroup").val(data.jobGroup);
methodName = 'edit';
index = n;
},
cancel:function (index, layero) {
$(".my_clear").val("");
layer.close(index)
}
});
} else if (layEvent == 'del') {// 删除
layer.confirm('确定删除吗???', {icon: 3, title: '提示'}, function (index) {
$.post( path + '/tScheduleTrigger/del', {
id: data.id
}, function (data) {
layer.close(index);
table.reload('quarzTableReload', {
page: {
curr: 1 // 重新从第 1 页开始
}
})
});
})
}
});
});
访问 http://localhost/tScheduleTrigger/toQuarztManagement
over