标签:snap maven put read turn 框架整合 scheduler names 定时任务
Spring整合Quartz
quartz调度框架是有内置表的,进入quartz的官网http://www.quartz-scheduler.org/,点击Downloads,下载后在目录\docs\dbTables下有常用数据库创建quartz表的脚本,例如:“tables_mysql.sql”
导入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.javaqi</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>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz-jobs</artifactId>
<version>2.2.1</version>
</dependency>
</dependencies>
<build>
<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>
<plugins>
<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>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
在项目中添加quartz.properties文件(这样就不会加载自带的properties文件)
此文件的内容主要分为:scheduler,ThreadPool,JobStore,plugin,Datasources等部分,
覆盖properties文件的目的是覆盖默认的数据源,更换为druid的数据配置
quartz.properties
1 # 2 #============================================================================ 3 # Configure Main Scheduler Properties 调度器属性 4 #============================================================================ 5 org.quartz.scheduler.instanceName: DefaultQuartzScheduler 6 org.quartz.scheduler.instanceId = AUTO 7 org.quartz.scheduler.rmi.export: false 8 org.quartz.scheduler.rmi.proxy: false 9 org.quartz.scheduler.wrapJobExecutionInUserTransaction: false 10 org.quartz.threadPool.class: org.quartz.simpl.SimpleThreadPool 11 org.quartz.threadPool.threadCount= 10 12 org.quartz.threadPool.threadPriority: 5 13 org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread: true 14 org.quartz.jobStore.misfireThreshold: 60000 15 #============================================================================ 16 # Configure JobStore 17 #============================================================================ 18 #存储方式使用JobStoreTX,也就是数据库 19 org.quartz.jobStore.class: org.quartz.impl.jdbcjobstore.JobStoreTX 20 org.quartz.jobStore.driverDelegateClass:org.quartz.impl.jdbcjobstore.StdJDBCDelegate 21 #使用自己的配置文件 22 org.quartz.jobStore.useProperties:true 23 #数据库中quartz表的表名前缀 24 org.quartz.jobStore.tablePrefix:qrtz_ 25 org.quartz.jobStore.dataSource:qzDS 26 #是否使用集群(如果项目只部署到 一台服务器,就不用了) 27 org.quartz.jobStore.isClustered = true 28 #============================================================================ 29 # Configure Datasources 30 #============================================================================ 31 #配置数据库源(org.quartz.dataSource.qzDS.maxConnections: c3p0配置的是有s的,druid数据源没有s) 32 org.quartz.dataSource.qzDS.connectionProvider.class:com.javaqi.quartz02.utils.DruidConnectionProvider 33 org.quartz.dataSource.qzDS.driver: com.mysql.jdbc.Driver 34 org.quartz.dataSource.qzDS.URL: jdbc:mysql://localhost:3306/xufanqi?useUnicode=true&characterEncoding=utf8 35 org.quartz.dataSource.qzDS.user: root 36 org.quartz.dataSource.qzDS.password: 123 37 org.quartz.dataSource.qzDS.maxConnection: 10
自定义MyJobFactory,解决spring不能在quartz中注入bean的问题
MyJobFactory
1 package com.javaqi.quartz02.utils; 2 3 import lombok.extern.slf4j.Slf4j; 4 import org.quartz.spi.TriggerFiredBundle; 5 import org.springframework.beans.factory.annotation.Autowired; 6 import org.springframework.beans.factory.config.AutowireCapableBeanFactory; 7 import org.springframework.scheduling.quartz.AdaptableJobFactory; 8 import org.springframework.stereotype.Component; 9 10 @Component 11 @Slf4j 12 public class MyJobFactory extends AdaptableJobFactory { 13 14 //这个对象Spring会帮我们自动注入进来 15 @Autowired 16 private AutowireCapableBeanFactory autowireCapableBeanFactory; 17 18 //重写创建Job任务的实例方法 19 @Override 20 protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception { 21 Object jobInstance = super.createJobInstance(bundle); 22 //通过以下方式,解决Job任务无法使用Spring中的Bean问题 23 autowireCapableBeanFactory.autowireBean(jobInstance); 24 return super.createJobInstance(bundle); 25 } 26 }
从数据库读取任务信息动态生成定时任务,和把quartz持久化到数据库是没有关系的。前者是我们自己定义的业务表,而后者是quartz使用自己的表来存储信息。持久化到数据库后,就算服务器重启或是多个quartz节点也没关系,因为他们共享数据库中的任务信息。
DruidConnectionProvider.java
1 package com.javaqi.quartz02.utils; 2 3 import com.alibaba.druid.pool.DruidDataSource; 4 import org.quartz.SchedulerException; 5 import org.quartz.utils.ConnectionProvider; 6 7 import java.sql.Connection; 8 import java.sql.SQLException; 9 10 /* 11 #============================================================================ 12 # JDBC 13 #============================================================================ 14 org.quartz.jobStore.driverDelegateClass:org.quartz.impl.jdbcjobstore.StdJDBCDelegate 15 org.quartz.jobStore.useProperties:false 16 org.quartz.jobStore.dataSource:qzDS 17 #org.quartz.dataSource.qzDS.connectionProvider.class:org.quartz.utils.PoolingConnectionProvider 18 org.quartz.dataSource.qzDS.connectionProvider.class:com.zking.q03.quartz.DruidConnectionProvider 19 org.quartz.dataSource.qzDS.driver:com.mysql.jdbc.Driver 20 org.quartz.dataSource.qzDS.URL:jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=UTF-8 21 org.quartz.dataSource.qzDS.user:root 22 org.quartz.dataSource.qzDS.password:root 23 org.quartz.dataSource.qzDS.maxConnections:30 24 org.quartz.dataSource.qzDS.validationQuery: select 0 25 */ 26 27 /** 28 * [Druid连接池的Quartz扩展类] 29 * 30 * @ProjectName: [] 31 * @Author: [xuguang] 32 * @CreateDate: [2015/11/10 17:58] 33 * @Update: [说明本次修改内容] BY[xuguang][2015/11/10] 34 * @Version: [v1.0] 35 */ 36 public class DruidConnectionProvider implements ConnectionProvider { 37 38 /* 39 * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 40 * 41 * 常量配置,与quartz.properties文件的key保持一致(去掉前缀),同时提供set方法,Quartz框架自动注入值。 42 * 43 * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 44 */ 45 46 //JDBC驱动 47 public String driver; 48 //JDBC连接串 49 public String URL; 50 //数据库用户名 51 public String user; 52 //数据库用户密码 53 public String password; 54 //数据库最大连接数 55 public int maxConnection; 56 //数据库SQL查询每次连接返回执行到连接池,以确保它仍然是有效的。 57 public String validationQuery; 58 59 private boolean validateOnCheckout; 60 61 private int idleConnectionValidationSeconds; 62 63 public String maxCachedStatementsPerConnection; 64 65 private String discardIdleConnectionsSeconds; 66 67 public static final int DEFAULT_DB_MAX_CONNECTIONS = 10; 68 69 public static final int DEFAULT_DB_MAX_CACHED_STATEMENTS_PER_CONNECTION = 120; 70 71 //Druid连接池 72 private DruidDataSource datasource; 73 74 /* 75 * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 76 * 77 * 接口实现 78 * 79 * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 80 */ 81 public Connection getConnection() throws SQLException { 82 return datasource.getConnection(); 83 } 84 85 public void shutdown() throws SQLException { 86 datasource.close(); 87 } 88 public void initialize() throws SQLException{ 89 if (this.URL == null) { 90 throw new SQLException("DBPool could not be created: DB URL cannot be null"); 91 } 92 93 if (this.driver == null) { 94 throw new SQLException("DBPool driver could not be created: DB driver class name cannot be null!"); 95 } 96 97 if (this.maxConnection < 0) { 98 throw new SQLException("DBPool maxConnectins could not be created: Max connections must be greater than zero!"); 99 } 100 101 datasource = new DruidDataSource(); 102 try{ 103 datasource.setDriverClassName(this.driver); 104 } catch (Exception e) { 105 try { 106 throw new SchedulerException("Problem setting driver class name on datasource: " + e.getMessage(), e); 107 } catch (SchedulerException e1) { 108 } 109 } 110 111 datasource.setUrl(this.URL); 112 datasource.setUsername(this.user); 113 datasource.setPassword(this.password); 114 datasource.setMaxActive(this.maxConnection); 115 datasource.setMinIdle(1); 116 datasource.setMaxWait(0); 117 datasource.setMaxPoolPreparedStatementPerConnectionSize(this.DEFAULT_DB_MAX_CACHED_STATEMENTS_PER_CONNECTION); 118 119 if (this.validationQuery != null) { 120 datasource.setValidationQuery(this.validationQuery); 121 if(!this.validateOnCheckout) 122 datasource.setTestOnReturn(true); 123 else 124 datasource.setTestOnBorrow(true); 125 datasource.setValidationQueryTimeout(this.idleConnectionValidationSeconds); 126 } 127 } 128 129 /* 130 * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 131 * 132 * 提供get set方法 133 * 134 * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 135 */ 136 public String getDriver() { 137 return driver; 138 } 139 140 public void setDriver(String driver) { 141 this.driver = driver; 142 } 143 144 public String getURL() { 145 return URL; 146 } 147 148 public void setURL(String URL) { 149 this.URL = URL; 150 } 151 152 public String getUser() { 153 return user; 154 } 155 156 public void setUser(String user) { 157 this.user = user; 158 } 159 160 public String getPassword() { 161 return password; 162 } 163 164 public void setPassword(String password) { 165 this.password = password; 166 } 167 168 public int getMaxConnection() { 169 return maxConnection; 170 } 171 172 public void setMaxConnection(int maxConnection) { 173 this.maxConnection = maxConnection; 174 } 175 176 public String getValidationQuery() { 177 return validationQuery; 178 } 179 180 public void setValidationQuery(String validationQuery) { 181 this.validationQuery = validationQuery; 182 } 183 184 public boolean isValidateOnCheckout() { 185 return validateOnCheckout; 186 } 187 188 public void setValidateOnCheckout(boolean validateOnCheckout) { 189 this.validateOnCheckout = validateOnCheckout; 190 } 191 192 public int getIdleConnectionValidationSeconds() { 193 return idleConnectionValidationSeconds; 194 } 195 196 public void setIdleConnectionValidationSeconds(int idleConnectionValidationSeconds) { 197 this.idleConnectionValidationSeconds = idleConnectionValidationSeconds; 198 } 199 200 public DruidDataSource getDatasource() { 201 return datasource; 202 } 203 204 public void setDatasource(DruidDataSource datasource) { 205 this.datasource = datasource; 206 } 207 }
QuartzConfiguration.java(quartz调度框架与spring框架整合的配置类,主要是要将org.quartz.Scheduler交给spring进行管理)
QuartzConfiguration
1 package com.javaqi.quartz02.config; 2 3 import com.javaqi.quartz02.utils.MyJobFactory; 4 import org.quartz.Scheduler; 5 import org.springframework.beans.factory.annotation.Autowired; 6 import org.springframework.beans.factory.config.PropertiesFactoryBean; 7 import org.springframework.context.annotation.Bean; 8 import org.springframework.context.annotation.Configuration; 9 import org.springframework.core.io.ClassPathResource; 10 import org.springframework.scheduling.quartz.SchedulerFactoryBean; 11 12 import java.io.IOException; 13 import java.util.Properties; 14 15 @Configuration 16 public class QuartzConfiguration { 17 18 @Autowired 19 private MyJobFactory myJobFactory; 20 21 //创建调度器工厂 22 @Bean 23 public SchedulerFactoryBean schedulerFactoryBean(){ 24 //1.创建SchedulerFactoryBean 25 //2.加载自定义的quartz.properties配置文件 26 //3.设置MyJobFactory 27 28 SchedulerFactoryBean factoryBean=new SchedulerFactoryBean(); 29 try { 30 factoryBean.setQuartzProperties(quartzProperties()); 31 factoryBean.setJobFactory(myJobFactory); 32 return factoryBean; 33 } catch (IOException e) { 34 throw new RuntimeException(e); 35 } 36 } 37 38 @Bean 39 public Properties quartzProperties() throws IOException { 40 PropertiesFactoryBean propertiesFactoryBean=new PropertiesFactoryBean(); 41 propertiesFactoryBean.setLocation(new ClassPathResource("/quartz.properties")); 42 propertiesFactoryBean.afterPropertiesSet(); 43 return propertiesFactoryBean.getObject(); 44 } 45 46 @Bean(name="scheduler") 47 public Scheduler scheduler(){ 48 return schedulerFactoryBean().getScheduler(); 49 } 50 }
配置application.yml
1 server: 2 servlet: 3 context-path: / 4 port: 80 5 spring: 6 datasource: 7 #1.JDBC 8 type: com.alibaba.druid.pool.DruidDataSource 9 driver-class-name: com.mysql.jdbc.Driver 10 url: jdbc:mysql://localhost:3306/xufanqi?useUnicode=true&characterEncoding=utf8 11 username: root 12 password: 123 13 druid: 14 #2.\u8FDE\u63A5\u6C60\u914D\u7F6E 15 #\u521D\u59CB\u5316\u8FDE\u63A5\u6C60\u7684\u8FDE\u63A5\u6570\u91CF \u5927\u5C0F\uFF0C\u6700\u5C0F\uFF0C\u6700\u5927 16 initial-size: 5 17 min-idle: 5 18 max-active: 20 19 #\u914D\u7F6E\u83B7\u53D6\u8FDE\u63A5\u7B49\u5F85\u8D85\u65F6\u7684\u65F6\u95F4 20 max-wait: 60000 21 #\u914D\u7F6E\u95F4\u9694\u591A\u4E45\u624D\u8FDB\u884C\u4E00\u6B21\u68C0\u6D4B\uFF0C\u68C0\u6D4B\u9700\u8981\u5173\u95ED\u7684\u7A7A\u95F2\u8FDE\u63A5\uFF0C\u5355\u4F4D\u662F\u6BEB\u79D2 22 time-between-eviction-runs-millis: 60000 23 # \u914D\u7F6E\u4E00\u4E2A\u8FDE\u63A5\u5728\u6C60\u4E2D\u6700\u5C0F\u751F\u5B58\u7684\u65F6\u95F4\uFF0C\u5355\u4F4D\u662F\u6BEB\u79D2 24 min-evictable-idle-time-millis: 30000 25 validation-query: SELECT 1 FROM DUAL 26 test-while-idle: true 27 test-on-borrow: true 28 test-on-return: false 29 # \u662F\u5426\u7F13\u5B58preparedStatement\uFF0C\u4E5F\u5C31\u662FPSCache \u5B98\u65B9\u5EFA\u8BAEMySQL\u4E0B\u5EFA\u8BAE\u5173\u95ED \u4E2A\u4EBA\u5EFA\u8BAE\u5982\u679C\u60F3\u7528SQL\u9632\u706B\u5899 \u5EFA\u8BAE\u6253\u5F00 30 pool-prepared-statements: true 31 max-pool-prepared-statement-per-connection-size: 20 32 # \u914D\u7F6E\u76D1\u63A7\u7EDF\u8BA1\u62E6\u622A\u7684filters\uFF0C\u53BB\u6389\u540E\u76D1\u63A7\u754C\u9762sql\u65E0\u6CD5\u7EDF\u8BA1\uFF0C‘wall‘\u7528\u4E8E\u9632\u706B\u5899 33 filter: 34 stat: 35 merge-sql: true 36 slow-sql-millis: 5000 37 #3.\u57FA\u7840\u76D1\u63A7\u914D\u7F6E 38 web-stat-filter: 39 enabled: true 40 url-pattern: /* 41 #\u8BBE\u7F6E\u4E0D\u7EDF\u8BA1\u54EA\u4E9BURL 42 exclusions: "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*" 43 session-stat-enable: true 44 session-stat-max-count: 100 45 stat-view-servlet: 46 enabled: true 47 url-pattern: /druid/* 48 reset-enable: true 49 #\u8BBE\u7F6E\u76D1\u63A7\u9875\u9762\u7684\u767B\u5F55\u540D\u548C\u5BC6\u7801 50 login-username: admin 51 login-password: admin 52 allow: 127.0.0.1 53 #deny: 192.168.1.100 54 55 #\u663E\u793A\u65E5\u5FD7 56 logging: 57 level: 58 com.javaqi.quartz02.mapper: debug
Quartz02Application.java
1 package com.javaqi.quartz02; 2 3 import org.mybatis.spring.annotation.MapperScan; 4 import org.springframework.boot.SpringApplication; 5 import org.springframework.boot.autoconfigure.SpringBootApplication; 6 import org.springframework.scheduling.annotation.EnableScheduling; 7 import org.springframework.transaction.annotation.EnableTransactionManagement; 8 9 @MapperScan("com.javaqi.quartz02.mapper") 10 @EnableTransactionManagement 11 @EnableScheduling 12 @SpringBootApplication 13 public class Quartz02Application { 14 15 public static void main(String[] args) { 16 SpringApplication.run(Quartz02Application.class, args); 17 } 18 19 }
逆向生成
generatorConfig.xml
1 <?xml version="1.0" encoding="UTF-8" ?> 2 <!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" 3 "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd" > 4 <generatorConfiguration> 5 <!-- 引入配置文件 --> 6 <properties resource="jdbc.properties"/> 7 8 <!--指定数据库jdbc驱动jar包的位置--> 9 <classPathEntry location="D:\apache-maven-3.5.0-bin\apache-maven-3.5.0-bin\Mvn_repository\mysql\mysql-connector-java\5.1.44\mysql-connector-java-5.1.44.jar"/> 10 11 <!-- 一个数据库一个context --> 12 <context id="infoGuardian"> 13 <!-- 注释 --> 14 <commentGenerator> 15 <property name="suppressAllComments" value="true"/><!-- 是否取消注释 --> 16 <property name="suppressDate" value="true"/> <!-- 是否生成注释代时间戳 --> 17 </commentGenerator> 18 19 <!-- jdbc连接 --> 20 <jdbcConnection driverClass="${jdbc.driver}" 21 connectionURL="${jdbc.url}" userId="${jdbc.username}" password="${jdbc.password}"/> 22 23 <!-- 类型转换 --> 24 <javaTypeResolver> 25 <!-- 是否使用bigDecimal, false可自动转化以下类型(Long, Integer, Short, etc.) --> 26 <property name="forceBigDecimals" value="false"/> 27 </javaTypeResolver> 28 29 <!-- 01 指定javaBean生成的位置 --> 30 <!-- targetPackage:指定生成的model生成所在的包名 --> 31 <!-- targetProject:指定在该项目下所在的路径 --> 32 <javaModelGenerator targetPackage="com.javaqi.quartz02.model" 33 targetProject="src/main/java"> 34 <!-- 是否允许子包,即targetPackage.schemaName.tableName --> 35 <property name="enableSubPackages" value="false"/> 36 <!-- 是否对model添加构造函数 --> 37 <property name="constructorBased" value="true"/> 38 <!-- 是否针对string类型的字段在set的时候进行trim调用 --> 39 <property name="trimStrings" value="false"/> 40 <!-- 建立的Model对象是否 不可改变 即生成的Model对象不会有 setter方法,只有构造方法 --> 41 <property name="immutable" value="false"/> 42 </javaModelGenerator> 43 44 <!-- 02 指定sql映射文件生成的位置 --> 45 <sqlMapGenerator targetPackage="com.javaqi.quartz02.mapper" 46 targetProject="src/main/java"> 47 <!-- 是否允许子包,即targetPackage.schemaName.tableName --> 48 <property name="enableSubPackages" value="false"/> 49 </sqlMapGenerator> 50 51 <!-- 03 生成XxxMapper接口 --> 52 <!-- type="ANNOTATEDMAPPER",生成Java Model 和基于注解的Mapper对象 --> 53 <!-- type="MIXEDMAPPER",生成基于注解的Java Model 和相应的Mapper对象 --> 54 <!-- type="XMLMAPPER",生成SQLMap XML文件和独立的Mapper接口 --> 55 <javaClientGenerator targetPackage="com.javaqi.quartz02.mapper" 56 targetProject="src/main/java" type="XMLMAPPER"> 57 <!-- 是否在当前路径下新加一层schema,false路径com.oop.eksp.user.model, true:com.oop.eksp.user.model.[schemaName] --> 58 <property name="enableSubPackages" value="false"/> 59 </javaClientGenerator> 60 61 <!-- 配置表信息 --> 62 <table schema="" tableName="t_schedule_trigger" domainObjectName="ScheduleTrigger" 63 enableCountByExample="false" enableDeleteByExample="false" 64 enableSelectByExample="false" enableUpdateByExample="false"> 65 <property name="useActualColumnNames" value="true" /> 66 </table> 67 <table schema="" tableName="t_schedule_trigger_param" domainObjectName="ScheduleTriggerParam" 68 enableCountByExample="false" enableDeleteByExample="false" 69 enableSelectByExample="false" enableUpdateByExample="false"> 70 <property name="useActualColumnNames" value="true" /> 71 </table> 72 73 </context> 74 </generatorConfiguration>
jdbc.properties
1 jdbc.driver=com.mysql.jdbc.Driver
2 jdbc.url=jdbc:mysql://localhost:3306/xufanqi?useUnicode=true&characterEncoding=UTF-8
3 jdbc.username=root
4 jdbc.password=123
ScheduleTriggerMapper.java
1 /** 2 * 查询触发器中包含的所有任务 3 * @return 4 */ 5 List<ScheduleTrigger> queryScheduleTriggerLst();
ScheduleTriggerMapper.xml
1 <?xml version="1.0" encoding="UTF-8" ?> 2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > 3 <mapper namespace="com.javaqi.quartz02.mapper.ScheduleTriggerMapper" > 4 <resultMap id="BaseResultMap" type="com.javaqi.quartz02.model.ScheduleTrigger" > 5 <constructor > 6 <idArg column="id" jdbcType="INTEGER" javaType="java.lang.Integer" /> 7 <arg column="cron" jdbcType="VARCHAR" javaType="java.lang.String" /> 8 <arg column="status" jdbcType="CHAR" javaType="java.lang.String" /> 9 <arg column="job_name" jdbcType="VARCHAR" javaType="java.lang.String" /> 10 <arg column="job_group" jdbcType="VARCHAR" javaType="java.lang.String" /> 11 </constructor> 12 </resultMap> 13 <sql id="Base_Column_List" > 14 id, cron, status, job_name, job_group 15 </sql> 16 <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" > 17 select 18 <include refid="Base_Column_List" /> 19 from t_schedule_trigger 20 where id = #{id,jdbcType=INTEGER} 21 </select> 22 <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" > 23 delete from t_schedule_trigger 24 where id = #{id,jdbcType=INTEGER} 25 </delete> 26 <insert id="insert" parameterType="com.javaqi.quartz02.model.ScheduleTrigger" > 27 insert into t_schedule_trigger (id, cron, status, 28 job_name, job_group) 29 values (#{id,jdbcType=INTEGER}, #{cron,jdbcType=VARCHAR}, #{status,jdbcType=CHAR}, 30 #{job_name,jdbcType=VARCHAR}, #{job_group,jdbcType=VARCHAR}) 31 </insert> 32 <insert id="insertSelective" parameterType="com.javaqi.quartz02.model.ScheduleTrigger" > 33 insert into t_schedule_trigger 34 <trim prefix="(" suffix=")" suffixOverrides="," > 35 <if test="id != null" > 36 id, 37 </if> 38 <if test="cron != null" > 39 cron, 40 </if> 41 <if test="status != null" > 42 status, 43 </if> 44 <if test="job_name != null" > 45 job_name, 46 </if> 47 <if test="job_group != null" > 48 job_group, 49 </if> 50 </trim> 51 <trim prefix="values (" suffix=")" suffixOverrides="," > 52 <if test="id != null" > 53 #{id,jdbcType=INTEGER}, 54 </if> 55 <if test="cron != null" > 56 #{cron,jdbcType=VARCHAR}, 57 </if> 58 <if test="status != null" > 59 #{status,jdbcType=CHAR}, 60 </if> 61 <if test="job_name != null" > 62 #{job_name,jdbcType=VARCHAR}, 63 </if> 64 <if test="job_group != null" > 65 #{job_group,jdbcType=VARCHAR}, 66 </if> 67 </trim> 68 </insert> 69 <update id="updateByPrimaryKeySelective" parameterType="com.javaqi.quartz02.model.ScheduleTrigger" > 70 update t_schedule_trigger 71 <set > 72 <if test="cron != null" > 73 cron = #{cron,jdbcType=VARCHAR}, 74 </if> 75 <if test="status != null" > 76 status = #{status,jdbcType=CHAR}, 77 </if> 78 <if test="job_name != null" > 79 job_name = #{job_name,jdbcType=VARCHAR}, 80 </if> 81 <if test="job_group != null" > 82 job_group = #{job_group,jdbcType=VARCHAR}, 83 </if> 84 </set> 85 where id = #{id,jdbcType=INTEGER} 86 </update> 87 <update id="updateByPrimaryKey" parameterType="com.javaqi.quartz02.model.ScheduleTrigger" > 88 update t_schedule_trigger 89 set cron = #{cron,jdbcType=VARCHAR}, 90 status = #{status,jdbcType=CHAR}, 91 job_name = #{job_name,jdbcType=VARCHAR}, 92 job_group = #{job_group,jdbcType=VARCHAR} 93 where id = #{id,jdbcType=INTEGER} 94 </update> 95 96 <select id="queryScheduleTriggerLst" resultType="com.javaqi.quartz02.model.ScheduleTrigger"> 97 select <include refid="Base_Column_List"/> 98 from t_schedule_trigger 99 </select> 100 </mapper>
ScheduleTriggerParamMapper
1 ** 2 * 查询出当前任务类对应所需的参数 3 * @param triggerId 4 * @return 5 */ 6 List<ScheduleTriggerParam> queryScheduleParamLst(Integer triggerId);
ScheduleTriggerParamMapper.xml
1 <?xml version="1.0" encoding="UTF-8" ?> 2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > 3 <mapper namespace="com.javaqi.quartz02.mapper.ScheduleTriggerParamMapper" > 4 <resultMap id="BaseResultMap" type="com.javaqi.quartz02.model.ScheduleTriggerParam" > 5 <constructor > 6 <idArg column="param_id" jdbcType="INTEGER" javaType="java.lang.Integer" /> 7 <arg column="name" jdbcType="VARCHAR" javaType="java.lang.String" /> 8 <arg column="value" jdbcType="VARCHAR" javaType="java.lang.String" /> 9 <arg column="schedule_trigger_id" jdbcType="INTEGER" javaType="java.lang.Integer" /> 10 </constructor> 11 </resultMap> 12 <sql id="Base_Column_List" > 13 param_id, name, value, schedule_trigger_id 14 </sql> 15 <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" > 16 select 17 <include refid="Base_Column_List" /> 18 from t_schedule_trigger_param 19 where param_id = #{param_id,jdbcType=INTEGER} 20 </select> 21 <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" > 22 delete from t_schedule_trigger_param 23 where param_id = #{param_id,jdbcType=INTEGER} 24 </delete> 25 <insert id="insert" parameterType="com.javaqi.quartz02.model.ScheduleTriggerParam" > 26 insert into t_schedule_trigger_param (param_id, name, value, 27 schedule_trigger_id) 28 values (#{param_id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}, #{value,jdbcType=VARCHAR}, 29 #{schedule_trigger_id,jdbcType=INTEGER}) 30 </insert> 31 <insert id="insertSelective" parameterType="com.javaqi.quartz02.model.ScheduleTriggerParam" > 32 insert into t_schedule_trigger_param 33 <trim prefix="(" suffix=")" suffixOverrides="," > 34 <if test="param_id != null" > 35 param_id, 36 </if> 37 <if test="name != null" > 38 name, 39 </if> 40 <if test="value != null" > 41 value, 42 </if> 43 <if test="schedule_trigger_id != null" > 44 schedule_trigger_id, 45 </if> 46 </trim> 47 <trim prefix="values (" suffix=")" suffixOverrides="," > 48 <if test="param_id != null" > 49 #{param_id,jdbcType=INTEGER}, 50 </if> 51 <if test="name != null" > 52 #{name,jdbcType=VARCHAR}, 53 </if> 54 <if test="value != null" > 55 #{value,jdbcType=VARCHAR}, 56 </if> 57 <if test="schedule_trigger_id != null" > 58 #{schedule_trigger_id,jdbcType=INTEGER}, 59 </if> 60 </trim> 61 </insert> 62 <update id="updateByPrimaryKeySelective" parameterType="com.javaqi.quartz02.model.ScheduleTriggerParam" > 63 update t_schedule_trigger_param 64 <set > 65 <if test="name != null" > 66 name = #{name,jdbcType=VARCHAR}, 67 </if> 68 <if test="value != null" > 69 value = #{value,jdbcType=VARCHAR}, 70 </if> 71 <if test="schedule_trigger_id != null" > 72 schedule_trigger_id = #{schedule_trigger_id,jdbcType=INTEGER}, 73 </if> 74 </set> 75 where param_id = #{param_id,jdbcType=INTEGER} 76 </update> 77 <update id="updateByPrimaryKey" parameterType="com.javaqi.quartz02.model.ScheduleTriggerParam" > 78 update t_schedule_trigger_param 79 set name = #{name,jdbcType=VARCHAR}, 80 value = #{value,jdbcType=VARCHAR}, 81 schedule_trigger_id = #{schedule_trigger_id,jdbcType=INTEGER} 82 where param_id = #{param_id,jdbcType=INTEGER} 83 </update> 84 85 <select id="queryScheduleParamLst" resultType="com.javaqi.quartz02.model.ScheduleTriggerParam"> 86 select <include refid="Base_Column_List"/> 87 from t_schedule_trigger_param where schedule_trigger_id=#{triggerId} 88 </select> 89 </mapper>
ScheduleTriggerParamServiceImpl.java
1 package com.javaqi.quartz02.service.impl; 2 3 import com.javaqi.quartz02.mapper.ScheduleTriggerParamMapper; 4 import com.javaqi.quartz02.model.ScheduleTriggerParam; 5 import com.javaqi.quartz02.service.ScheduleTriggerParamService; 6 import org.springframework.beans.factory.annotation.Autowired; 7 import org.springframework.stereotype.Service; 8 9 import java.util.List; 10 11 /** 12 * @author XuFanQi 13 * @site 14 * @company 15 * @create 2019-12-03 14:58 16 */ 17 @Service 18 public class ScheduleTriggerParamServiceImpl implements ScheduleTriggerParamService { 19 20 @Autowired 21 private ScheduleTriggerParamMapper scheduleTriggerParamMapper; 22 23 @Override 24 public List<ScheduleTriggerParam> queryScheduleParamLst(Integer triggerId) { 25 return scheduleTriggerParamMapper.queryScheduleParamLst(triggerId); 26 } 27 }
spring自带定时任务作业类ScheduleTriggerServiceImpl.java(重点)
1 package com.javaqi.quartz02.service.impl; 2 3 import com.javaqi.quartz02.mapper.ScheduleTriggerMapper; 4 import com.javaqi.quartz02.mapper.ScheduleTriggerParamMapper; 5 import com.javaqi.quartz02.model.ScheduleTrigger; 6 import com.javaqi.quartz02.model.ScheduleTriggerParam; 7 import com.javaqi.quartz02.service.ScheduleTriggerService; 8 import org.quartz.*; 9 import org.springframework.beans.factory.annotation.Autowired; 10 import org.springframework.scheduling.annotation.Scheduled; 11 import org.springframework.stereotype.Service; 12 13 import java.util.List; 14 15 /** 16 * @author XuFanQi 17 * @site 18 * @company 19 * @create 2019-12-03 17:29 20 */ 21 @Service 22 public class ScheduleTriggerMapperImpl implements ScheduleTriggerService { 23 @Autowired 24 private ScheduleTriggerMapper scheduleTriggerMapper; 25 26 @Autowired 27 private ScheduleTriggerParamMapper scheduleTriggerParamMapper; 28 29 @Autowired 30 private Scheduler scheduler; 31 @Override 32 public int deleteByPrimaryKey(Integer id) { 33 return 0; 34 } 35 36 @Override 37 public int insert(ScheduleTrigger record) { 38 return 0; 39 } 40 41 @Override 42 public int insertSelective(ScheduleTrigger record) { 43 return 0; 44 } 45 46 @Override 47 public ScheduleTrigger selectByPrimaryKey(Integer id) { 48 return null; 49 } 50 51 @Override 52 public int updateByPrimaryKeySelective(ScheduleTrigger record) { 53 return 0; 54 } 55 56 @Override 57 public int updateByPrimaryKey(ScheduleTrigger record) { 58 return 0; 59 } 60 61 @Override 62 public List<ScheduleTrigger> queryScheduleTriggerLst() { 63 return null; 64 } 65 @Scheduled(cron = "0/10 * * * * ?") 66 public void refreshScheduler(){ 67 try { 68 List<ScheduleTrigger> scheduleTriggers = 69 scheduleTriggerMapper.queryScheduleTriggerLst(); 70 if(null!=scheduleTriggers){ 71 for (ScheduleTrigger scheduleTrigger : scheduleTriggers) { 72 String cron = scheduleTrigger.getCron(); //表达式 73 String jobName = scheduleTrigger.getJob_name(); //任务名称 74 String jobGroup = scheduleTrigger.getJob_group(); //任务分组 75 String status = scheduleTrigger.getStatus(); //任务状态 76 77 //JobName+JobGroup=Primary Key 78 //根据jobName和jobGroup生成TriggerKey 79 TriggerKey triggerKey = 80 TriggerKey.triggerKey(jobName, jobGroup); 81 //根据TriggerKey到Scheduler调度器中获取触发器 82 CronTrigger cronTrigger = (CronTrigger) 83 scheduler.getTrigger(triggerKey); 84 85 if(null==cronTrigger){ 86 if(status.equals("0")) 87 continue; 88 System.out.println("创建调度器"); 89 //创建任务详情 90 JobDetail jobDetail= 91 JobBuilder.newJob((Class<? extends Job>) Class.forName(jobName)) 92 .withIdentity(jobName,jobGroup) 93 .build(); 94 95 //往Job任务中传递参数 96 JobDataMap jobDataMap = jobDetail.getJobDataMap(); 97 List<ScheduleTriggerParam> params = 98 scheduleTriggerParamMapper.queryScheduleParamLst(scheduleTrigger.getId()); 99 for (ScheduleTriggerParam param : params) { 100 jobDataMap.put(param.getName(),param.getValue()); 101 } 102 103 //创建表达式调度器 104 CronScheduleBuilder cronSchedule = 105 CronScheduleBuilder.cronSchedule(cron); 106 107 //创建Trigger 108 cronTrigger=TriggerBuilder.newTrigger() 109 .withIdentity(jobName,jobGroup) 110 .withSchedule(cronSchedule) 111 .build(); 112 113 //将jobDetail和Trigger注入到scheduler调度器中 114 scheduler.scheduleJob(jobDetail,cronTrigger); 115 }else{ 116 System.err.println("Quartz 调度任务中已存在该任务"); 117 if(status.equals("0")){ 118 JobKey jobKey = JobKey.jobKey(jobName, jobGroup); 119 scheduler.deleteJob(jobKey); 120 continue; 121 } 122 //调度器中的表达式 123 String cronExpression = 124 cronTrigger.getCronExpression(); 125 126 if(!cron.equals(cronExpression)){ 127 //创建表达式调度器 128 CronScheduleBuilder cronSchedule = 129 CronScheduleBuilder.cronSchedule(cron); 130 131 //重构 132 cronTrigger=cronTrigger.getTriggerBuilder() 133 .withIdentity(triggerKey) 134 .withSchedule(cronSchedule) 135 .build(); 136 137 //刷新调度器 138 scheduler.rescheduleJob(triggerKey,cronTrigger); 139 } 140 } 141 } 142 } 143 } catch (Exception e) { 144 e.printStackTrace(); 145 } 146 } 147 }
t_schedule_trigger
MyJob.java
1 package com.javaqi.quartz02.quarzt; 2 3 import lombok.extern.slf4j.Slf4j; 4 import org.quartz.Job; 5 import org.quartz.JobExecutionContext; 6 import org.quartz.JobExecutionException; 7 import org.springframework.stereotype.Component; 8 9 import java.util.Date; 10 11 @Component 12 @Slf4j 13 public class MyJob implements Job { 14 15 @Override 16 public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException { 17 System.out.println("MyJob是一个空的任务计划,时间:"+new Date().toLocaleString()); 18 } 19 }
Spring自带定时任务每10s执行一次,查询自定义触发器表,获取到具体的作业类及任务表达式,quartz的任务为每5s执行一次
更改数据库调度器表t_schedule_trigger的state状态
当禁用该触发器时,那么程序只会执行spring自带的定时任务,每10s执行一次查询
MyJob1
1 package com.javaqi.quartz02.quarzt; 2 3 import com.javaqi.quartz02.service.ScheduleTriggerParamService; 4 import lombok.extern.slf4j.Slf4j; 5 import org.quartz.*; 6 import org.springframework.beans.factory.annotation.Autowired; 7 import org.springframework.stereotype.Component; 8 9 import java.util.Date; 10 11 @Component 12 @Slf4j 13 public class MyJob1 implements Job { 14 15 @Autowired 16 private ScheduleTriggerParamService scheduleTriggerParamService; 17 18 @Override 19 public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException { 20 JobDetail jobDetail = 21 jobExecutionContext.getJobDetail(); 22 JobDataMap jobDataMap = jobDetail.getJobDataMap(); 23 System.err.println(new Date().toLocaleString()+"-->携带参数个数:"+jobDataMap.size()); 24 } 25 }
程序执行spring自带的定时任务,每10s执行一次查询,查询t_schedule_trigger表,调度器表中有两个调度器,都是每5s执行一次,其中一个调度器是需要携带参数的,携带的参数在t_schedule_trigger_param表中,所以一开始调度器启动的时候需要查询t_schedule_trigger_param表数据
t_schedule_trigger_param
MyJob2
1 package com.javaqi.quartz02.quarzt; 2 3 import lombok.extern.slf4j.Slf4j; 4 import org.quartz.*; 5 import org.springframework.stereotype.Component; 6 7 import java.util.Date; 8 9 /** 10 * @author XuFanQi 11 * @site 12 * @company 13 * @create 2019-12-03 15:58 14 */ 15 @Component 16 @Slf4j 17 public class MyJob2 implements Job { 18 @Override 19 public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException { 20 JobDetail jobDetail = 21 jobExecutionContext.getJobDetail(); 22 JobDataMap jobDataMap = jobDetail.getJobDataMap(); 23 System.out.println(new Date().toLocaleString()+"-->MyJob2参数传递name="+jobDataMap.get("name")+",score="+ 24 jobDataMap.get("score")); 25 } 26 }
QuartzController
1 package com.javaqi.quartz02.Controller; 2 3 import com.javaqi.quartz02.model.ScheduleTrigger; 4 import com.javaqi.quartz02.service.ScheduleTriggerService; 5 import org.springframework.beans.factory.annotation.Autowired; 6 import org.springframework.stereotype.Controller; 7 import org.springframework.web.bind.annotation.PathVariable; 8 import org.springframework.web.bind.annotation.RequestMapping; 9 import org.springframework.web.servlet.ModelAndView; 10 11 import java.util.List; 12 13 @Controller 14 @RequestMapping("/quartz") 15 public class QuartzController { 16 17 @Autowired 18 private ScheduleTriggerService scheduleTriggerService; 19 20 @RequestMapping("/list") 21 public ModelAndView getAll() { 22 ModelAndView modelAndView = new ModelAndView(); 23 List<ScheduleTrigger> list = scheduleTriggerService.queryScheduleTriggerLst(); 24 modelAndView.addObject("quartzList", list); 25 modelAndView.setViewName("/index"); 26 return modelAndView; 27 } 28 29 @RequestMapping("/edit") 30 public String editStatus(ScheduleTrigger scheduleTrigger) { 31 int n = scheduleTriggerService.updateByPrimaryKeySelective(scheduleTrigger); 32 return "redirect:/quartz/list"; 33 } 34 35 @RequestMapping("/proSave/{id}") 36 public ModelAndView proSave(@PathVariable(value = "id") Integer id) { 37 ModelAndView modelAndView = new ModelAndView(); 38 ScheduleTrigger scheduleTrigger = scheduleTriggerService.selectByPrimaryKey(id); 39 modelAndView.addObject("schedule", scheduleTrigger); 40 modelAndView.setViewName("/edit"); 41 return modelAndView; 42 } 43 }
HTML前端
index.html
1 <!DOCTYPE html> 2 <html xmlns:th="http://www.thymeleaf.org"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>quartz定时任务管理</title> 6 </head> 7 <body> 8 <h1 style="text-align: center">定时任务管理</h1> 9 <table style="text-align: center" align="center" border="1px" width="80%"> 10 <tr> 11 <td>任务id</td> 12 <td>任务表达式</td> 13 <td>任务状态</td> 14 <td>job工作类</td> 15 <td>job分组</td> 16 <td>操作</td> 17 </tr> 18 <tr th:each="q : ${quartzList}"> 19 <td th:text="${q.id}"></td> 20 <td th:text="${q.cron}"></td> 21 <td th:text="${q.status}"></td> 22 <td th:text="${q.job_name}"></td> 23 <td th:text="${q.job_group}"></td> 24 <td th:switch ="${q.status} == 0"> 25 <a th:case="true" th:href="@{/quartz/edit(id=${q.id},status=1)}">启动</a> 26 <a th:case="false" th:href="@{/quartz/edit(id=${q.id},status=0)}">停止</a> 27 <a th:href="@{‘/quartz/proSave/‘+${q.id}}">编辑</a> 28 </td> 29 </tr> 30 </table> 31 32 33 </body> 34 </html>
修改
edit.html
1 <!DOCTYPE html> 2 <html xmlns:th="http://www.thymeleaf.org"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>编辑定时任务</title> 6 </head> 7 <body> 8 <h1>编辑定时任务</h1> 9 <form th:action="@{/quartz/edit}" method="post"> 10 <input type="hidden" name="id" th:value="${schedule.id}" /> 11 任务表达式: <input width="300px" type="text" name="cron" th:value="${schedule.cron}" /></br> 12 job工作类: <input width="300px" type="text" name="job_name" th:value="${schedule.job_name}" /></br> 13 job分组:<input width="300px" type="text" name="job_group" th:value="${schedule.job_group}" /></br> 14 <input type="submit" value="提交"/> 15 </form> 16 </body> 17 </html>
浏览器效果
标签:snap maven put read turn 框架整合 scheduler names 定时任务
原文地址:https://www.cnblogs.com/xcn123/p/11978962.html