Springboot+Quartz+MySql整合页面版
目的:
springboot整合Quartz
连接mysql整合出页面版
springboot整合Quartz
新建一个springboot项目来
导入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.2.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.qz</groupId>
<artifactId>quartz02</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>quartz02</name>
<description>Demo project for Spring Boot</description> <properties>
<java.version>1.8</java.version>
<mysql.version>5.1.44</mysql.version>
</properties> <dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-quartz</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.1</version>
</dependency> <dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz-jobs</artifactId>
<version>2.2.1</version>
</dependency> <dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin> <plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.2</version>
<dependencies>
<!--使用Mybatis-generator插件不能使用太高版本的mysql驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
</dependencies>
<configuration>
<overwrite>true</overwrite>
</configuration>
</plugin>
</plugins>
<resources>
<resource>
<directory>src/main/resources</directory>
</resource>
<!--解决mybatis-generator-maven-plugin运行时没有将XxxMapper.xml文件放入target文件夹的问题-->
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
<!--解决mybatis-generator-maven-plugin运行时没有将jdbc.properites文件放入target文件夹的问题-->
<resource>
<directory>src/main/resources</directory>
<includes>
<include>*.properties</include>
<include>*.xml</include>
<include>*.yml</include>
</includes>
</resource>
</resources>
</build>
</project>
修改连接池为druid
一般quartz的默认连接池是才c3p0,如果用默认连接池就不需要修改了,但是我这里要使用druid连接池
Druid连接池Quartz的工具类
DruidConnectionProvider
package com.qz.quartz02.utils; 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.zking.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;
}
}
在项目开发中是需要在Job中操作数据库的,那么当然需要把它交给spring管理,
但是quartz本身是不支持的,所以我们需要修改它的底层代码,让我们的Job类能被spring所管理
MyJobFactory
package com.qz.quartz02.utils; 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);
return super.createJobInstance(bundle);
}
}
quartz.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.qz.quartz02.utils.DruidConnectionProvider
org.quartz.dataSource.qzDS.driver: com.mysql.jdbc.Driver
org.quartz.dataSource.qzDS.URL: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8
org.quartz.dataSource.qzDS.user: root
org.quartz.dataSource.qzDS.password: root
org.quartz.dataSource.qzDS.maxConnection: 10
QuartzConfiguration
把刚刚配置的东西都加到这个类里面来
package com.qz.quartz02.config; import com.qz.quartz02.utils.MyJobFactory;
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();
}
}
添加配置文件generatorConfig.xml
让mybatis逆向生成代码
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd" >
<generatorConfiguration>
<!-- 引入配置文件 -->
<properties resource="jdbc.properties"/> <!--指定数据库jdbc驱动jar包的位置-->
<classPathEntry location="E:\Maven\maven_cang\mysql\mysql-connector-java\5.1.44"/> <!-- 一个数据库一个context -->
<context id="infoGuardian">
<!-- 注释 -->
<commentGenerator>
<property name="suppressAllComments" value="true"/><!-- 是否取消注释 -->
<property name="suppressDate" value="true"/> <!-- 是否生成注释代时间戳 -->
</commentGenerator> <!-- jdbc连接 -->
<jdbcConnection driverClass="${jdbc.driver}"
connectionURL="${jdbc.url}" userId="${jdbc.username}" password="${jdbc.password}"/> <!-- 类型转换 -->
<javaTypeResolver>
<!-- 是否使用bigDecimal, false可自动转化以下类型(Long, Integer, Short, etc.) -->
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver> <!-- 01 指定javaBean生成的位置 -->
<!-- targetPackage:指定生成的model生成所在的包名 -->
<!-- targetProject:指定在该项目下所在的路径 -->
<javaModelGenerator targetPackage="com.qz.quartz02.model"
targetProject="src/main/java">
<!-- 是否允许子包,即targetPackage.schemaName.tableName -->
<property name="enableSubPackages" value="false"/>
<!-- 是否对model添加构造函数 -->
<property name="constructorBased" value="true"/>
<!-- 是否针对string类型的字段在set的时候进行trim调用 -->
<property name="trimStrings" value="false"/>
<!-- 建立的Model对象是否 不可改变 即生成的Model对象不会有 setter方法,只有构造方法 -->
<property name="immutable" value="false"/>
</javaModelGenerator> <!-- 02 指定sql映射文件生成的位置 -->
<sqlMapGenerator targetPackage="com.qz.quartz02.mapper"
targetProject="src/main/java">
<!-- 是否允许子包,即targetPackage.schemaName.tableName -->
<property name="enableSubPackages" value="false"/>
</sqlMapGenerator> <!-- 03 生成XxxMapper接口 -->
<!-- type="ANNOTATEDMAPPER",生成Java Model 和基于注解的Mapper对象 -->
<!-- type="MIXEDMAPPER",生成基于注解的Java Model 和相应的Mapper对象 -->
<!-- type="XMLMAPPER",生成SQLMap XML文件和独立的Mapper接口 -->
<javaClientGenerator targetPackage="com.qz.quartz02.mapper"
targetProject="src/main/java" type="XMLMAPPER">
<!-- 是否在当前路径下新加一层schema,false路径com.oop.eksp.user.model, true:com.oop.eksp.user.model.[schemaName] -->
<property name="enableSubPackages" value="false"/>
</javaClientGenerator> <!-- 配置表信息 -->
<table schema="" tableName="t_schedule_trigger" domainObjectName="ScheduleTrigger"
enableCountByExample="false" enableDeleteByExample="false"
enableSelectByExample="false" enableUpdateByExample="false">
<property name="useActualColumnNames" value="true" />
</table>
<table schema="" tableName="t_schedule_trigger_param" domainObjectName="ScheduleTriggerParam"
enableCountByExample="false" enableDeleteByExample="false"
enableSelectByExample="false" enableUpdateByExample="false">
<property name="useActualColumnNames" value="true" />
</table> </context>
</generatorConfiguration>
jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8
jdbc.username=root
jdbc.password=root
jdbc.initialSize=10
jdbc.maxTotal=100
jdbc.maxIdle=50
jdbc.minIdle=10
jdbc.maxWaitMillis=-1
然后在对应的mapper加入方法去实现
ScheduleTriggerMapper
/**
* 查询出当前任务类对应所需的参数
* @param triggerId
* @return
*/
/**
* 查询触发器中包含的所有任务
* @return
*/
List<ScheduleTrigger> queryScheduleTriggerLst();
ScheduleTriggerParamMapper
/**
* 查询触发器中包含的所有任务
* @return
*/
List<ScheduleTrigger> queryScheduleTriggerLst(); /**
* 查询出当前任务类对应所需的参数
* @param triggerId
* @return
*/
List<ScheduleTriggerParam> queryScheduleParamLst(Integer triggerId);
连接mysql整合出页面版
搞两个表来给案例测试
链接:https://pan.baidu.com/s/1ENUiBUTaa9TE0BzEgUHLuQ
提取码:zyp3
上面逆向生成了相关代码
我们写逻辑层就好啦
job类
myjob
package com.qz.quartz02.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.err.println("MyJob是一个空的任务计划,时间:"+new Date().toLocaleString());
}
}
myjob1
package com.qz.quartz02.job;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.springframework.stereotype.Component;
import java.util.Date; @Component
@Slf4j
public class MyJob1 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());
}
}
myjob2
package com.qz.quartz02.job; import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.springframework.stereotype.Component; import java.util.Date; @Component
@Slf4j
public class MyJob2 implements Job {
@Override
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
JobDetail jobDetail =
jobExecutionContext.getJobDetail();
JobDataMap jobDataMap = jobDetail.getJobDataMap();
System.out.println(new Date().toLocaleString()+"-->MyJob2参数传递name="+jobDataMap.get("name")+",score="+
jobDataMap.get("score"));
}
}
service业务逻辑层
ScheduleTriggerService
package com.qz.quartz02.service; import com.qz.quartz02.entity.ScheduleTrigger; import java.util.List; public interface ScheduleTriggerService {
int deleteByPrimaryKey(Integer id); int insert(ScheduleTrigger record); int insertSelective(ScheduleTrigger record); ScheduleTrigger selectByPrimaryKey(Integer id); int updateByPrimaryKeySelective(ScheduleTrigger record); int updateByPrimaryKey(ScheduleTrigger record); /**
* 查询触发器中包含的所有任务
* @return
*/
List<ScheduleTrigger> queryScheduleTriggerLst();
}
ScheduleTriggerServiceipml
package com.qz.quartz02.service.ipml; import com.qz.quartz02.mapper.ScheduleTriggerMapper;
import com.qz.quartz02.mapper.ScheduleTriggerParamMapper;
import com.qz.quartz02.model.ScheduleTrigger;
import com.qz.quartz02.model.ScheduleTriggerParam;
import com.qz.quartz02.service.ScheduleTriggerService;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service; import java.util.List; @Service
public class ScheduleTriggerServiceImpl implements ScheduleTriggerService { @Autowired
private ScheduleTriggerMapper scheduleTriggerMapper; @Autowired
private ScheduleTriggerParamMapper scheduleTriggerParamMapper; @Autowired
private Scheduler scheduler; @Scheduled(cron = "0/10 * * * * ?")
public void refreshScheduler(){
try {
List<ScheduleTrigger> scheduleTriggers =
scheduleTriggerMapper.queryScheduleTriggerLst();
if(null!=scheduleTriggers){
for (ScheduleTrigger scheduleTrigger : scheduleTriggers) {
String cron = scheduleTrigger.getCron(); //表达式
String jobName = scheduleTrigger.getJob_name(); //任务名称
String jobGroup = scheduleTrigger.getJob_group(); //任务分组
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){
// 1是要将自己业务表的数据同步到quartz内置表中去
// 0是不需要结束当前循环
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<ScheduleTriggerParam> params =
scheduleTriggerParamMapper.queryScheduleParamLst(scheduleTrigger.getId());
for (ScheduleTriggerParam 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();
}
} @Override
public int deleteByPrimaryKey(Integer id) {
return scheduleTriggerMapper.deleteByPrimaryKey(id);
} @Override
public int insert(ScheduleTrigger record) {
return scheduleTriggerMapper.insert(record);
} @Override
public int insertSelective(ScheduleTrigger record) {
return scheduleTriggerMapper.insertSelective(record);
} @Override
public ScheduleTrigger selectByPrimaryKey(Integer id) {
return scheduleTriggerMapper.selectByPrimaryKey(id);
} @Override
public int updateByPrimaryKeySelective(ScheduleTrigger record) {
return scheduleTriggerMapper.updateByPrimaryKeySelective(record);
} @Override
public int updateByPrimaryKey(ScheduleTrigger record) {
return scheduleTriggerMapper.updateByPrimaryKey(record);
} @Override
public List<ScheduleTrigger> queryScheduleTriggerLst() {
return scheduleTriggerMapper.queryScheduleTriggerLst();
}
}
QuartzController
package com.qz.quartz02.controller; import com.qz.quartz02.entity.ScheduleTrigger;
import com.qz.quartz02.service.ScheduleTriggerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView; import java.util.List; @Controller
@RequestMapping("/quartz")
public class QuartzController { @Autowired
private ScheduleTriggerService scheduleTriggerService; @RequestMapping("/list")
public ModelAndView getAll(){
ModelAndView mv = new ModelAndView();
List<ScheduleTrigger> list = scheduleTriggerService.queryScheduleTriggerLst();
mv.addObject("quartzList",list);
mv.setViewName("list");
return mv;
} @RequestMapping("/edit")
public String editStatus(ScheduleTrigger scheduleTrigger){
int n = scheduleTriggerService.updateByPrimaryKeySelective(scheduleTrigger);
return "redirect:/quartz/list";
} @RequestMapping("/proSave/{id}")
public ModelAndView proSave(@PathVariable(value = "id") Integer id){
ModelAndView mv=new ModelAndView();
ScheduleTrigger scheduleTrigger = scheduleTriggerService.selectByPrimaryKey(id);
mv.addObject("schedule",scheduleTrigger);
mv.setViewName("edit");
return mv;
} }
前端页面
list.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>quartz定时任务管理</title>
</head>
<body>
<h1 style="text-align: center">定时任务管理</h1>
<table style="text-align: center" align="center" border="1px" width="50%">
<tr>
<td>id</td>
<td>规则表达式</td>
<td>状态</td>
<td>工作类</td>
<td>分组</td>
<td>操作</td>
</tr>
<tr th:each="q : ${quartzList}">
<td th:text="${q.id}"></td>
<td th:text="${q.cron}"></td>
<td th:text="${q.status}"></td>
<td th:text="${q.job_name}"></td>
<td th:text="${q.job_group}"></td>
<td th:switch ="${q.status} == 0">
<a th:case="true" th:href="@{/quartz/edit(id=${q.id},status=1)}">启动</a>
<a th:case="false" th:href="@{/quartz/edit(id=${q.id},status=0)}">停止</a>
<a th:href="@{'/quartz/proSave/'+${q.id}}">编辑</a>
</td>
</tr>
</table> </body>
</html>
edit.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>编辑定时任务</title>
</head>
<body>
<h1>编辑定时任务</h1>
<form th:action="@{/quartz/edit}" method="post">
<input type="hidden" name="id" th:value="${schedule.id}" />
规则: <input width="300px" type="text" name="cron" th:value="${schedule.cron}" /></br>
工作类: <input width="300px" type="text" name="job_name" th:value="${schedule.job_name}" /></br>
分组:<input width="300px" type="text" name="job_group" th:value="${schedule.job_group}" /></br>
<input type="submit" value="提交"/>
</form>
</body>
</html>
效果:
谢谢观看!!
Springboot+Quartz+MySql整合页面版的更多相关文章
- spring-boot+quartz的CRUD动态任务管理系统
版权声明:作者: 小柒 出处: https://blog.52itstyle.com 分享是快乐的,也见证了个人成长历程,文章大多都是工作经验总结以及平时学习积累,基于自身认知不足之处在所难免,也请大 ...
- Springboot quartz集群(3) — 多节点发送邮件
本期将提供quartz集群能力 集群案例分析: 上一期的邮件发送功能,若在服务需要部署多节点,但定时任务不支持集群,因此,多节点定时任务势必会同时运行, 若向用户发送邮件通知,这种情况下会向用户发送两 ...
- 基于springboot+bootstrap+mysql+redis搭建一套完整的权限架构【六】【引入bootstrap前端框架】
https://blog.csdn.net/linzhefeng89/article/details/78752658 基于springboot+bootstrap+mysql+redis搭建一套完整 ...
- springboot+jpa+mysql+redis+swagger整合步骤
springboot+jpa+MySQL+swagger框架搭建好之上再整合redis: 在电脑上先安装redis: 一.在pom.xml中引入redis 二.在application.yml里配置r ...
- springboot+jpa+mysql+swagger整合
Springboot+jpa+MySQL+swagger整合 创建一个springboot web项目 <dependencies> <dependency> < ...
- Springboot+Mybatis+MySQL实例练习时踩坑记录
最近刚开始学习后端,直接让上手学习Springboot+Mybatis+MySQL对CRUD的实例,虽然实例不难,但是上面的三个知识我都不懂,就有点为难我了 所以经常遇到一个点卡自己很久的情况,这里列 ...
- SpringBoot Docker Mysql安装,Docker安装Mysql
SpringBoot Docker Mysql安装,Docker安装Mysql ================================ ©Copyright 蕃薯耀 2018年4月8日 ht ...
- 微服务之分布式跟踪系统(springboot+zipkin+mysql)
通过上一节<微服务之分布式跟踪系统(springboot+zipkin)>我们简单熟悉了zipkin的使用,但是收集的数据都保存在内存中重启后数据丢失,不过zipkin的Storage除了 ...
- springboot成神之——springboot+mybatis+mysql搭建项目简明demo
springboot+mybatis+mysql搭建项目简明demo 项目所需目录结构 pom.xml文件配置 application.properties文件配置 MyApplication.jav ...
随机推荐
- CSS3背景图片(多重背景、起始位置、裁剪、尺寸)
一.多重背景图片 ①CSS3允许我们在一个元素上添加多个图片 ②多重背景可以把多个图片资源添加到background属性上,用逗号隔开,然后用background-position把他们定位到你想要的 ...
- 4-微信小程序开发(小程序默认页面函数说明)
https://www.cnblogs.com/yangfengwu/p/11601299.html 源码下载链接: 或者 首先说一下,怎么让自己的一个项目更改名字成为一个新的项目 然后用软件导入项目 ...
- CF888G 【Xor-MST】
妙妙题-- 看到\(MST\),想到\(Kruskal\),看到异或,想到\(Trie\) 首先我们模拟一下\(Kruskal\)的流程:找到最小边,如果联通就忽略,未联通就加边 我们把所有点权值加入 ...
- 1、kafka概述
一.关于消息队列 消息队列是一种应用间的通信方式,消息就是是指在应用之间传送的数据,它也是进程通信的一种重要的方式. 1.消息队列的基本架构 producer:消息生产者. broker:消息处理中心 ...
- go的接口内部实现
1 前言 1.1 Go汇编 Go语言被定义为一门系统编程语言,与C语言一样通过编译器生成可直接运行的二进制文件.这一点与Java,PHP,Python等编程语言存在很大的不同,这些语言都是运行在基于C ...
- Echarts的简单入门
5 分钟上手 ECharts 获取 ECharts 你可以通过以下几种方式获取 ECharts. 从官网下载界面选择你需要的版本下载,根据开发者功能和体积上的需求,我们提供了不同打包的下载,如果你在体 ...
- 刷题记录:[CISCN2019 总决赛 Day2 Web1]Easyweb
目录 刷题记录:[CISCN2019 总决赛 Day2 Web1]Easyweb 一.涉及知识点 1.敏感文件泄露 2.绕过及sql注入 3.文件上传:短标签绕过php过滤 刷题记录:[CISCN20 ...
- Python 拼接字符串的几种方式
在学习Python(3x)的过程中,在拼接字符串的时候遇到了些问题,所以抽点时间整理一下Python 拼接字符串的几种方式. 方式1,使用加号(+)连接,使用加号连接各个变量或者元素必须是字符串类型( ...
- mysql性能测试-------重要!!!
我们在做性能测试的目的是什么,就是要测出一个系统的瓶颈在哪里,到底是哪里影响了我们系统的性能,找到问题,然后解决它.当然一个系统由很多东西一起组合到一起,应用程序.数据库.服务器.中中间件等等很多东西 ...
- https://www.cnblogs.com/LBSer/p/3310455.html
https://www.cnblogs.com/LBSer/p/3310455.html