热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

SpringBoot(10)quartz定时任务的配置和使用

quartz定时任务的配置与使用有存在一类需求,是需要去定时执行的,此时就需要使用到定时任务。例如说,每分钟扫描超时支付的订单ÿ

quartz定时任务的配置与使用

有存在一类需求,是需要去定时执行的,此时就需要使用到定时任务。例如说,每分钟扫描超时支付的订单,每小时清理一次日志文件,每天统计前一天的数据并生成报表,每个月月初的工资单的推送,每年一次的生日提醒等等。

Quartz 是一个开源的作业调度框架,它完全由 Java 写成,并设计用于 J2SE 和 J2EE 应用中。它提供了巨大的灵活性而不牺牲简单性。你能够用它来为执行一个作业而创建简单的或复杂的调度。

它有很多特征,如:数据库支持,集群,插件,EJB 作业预构建,JavaMail 及其它,支持 cron-like 表达式等等。

在 Quartz 体系结构中,有三个组件非常重要:


  • Scheduler :调度器
  • Trigger :触发器
  • Job :任务

1、导入依赖


<project xmlns&#61;"http://maven.apache.org/POM/4.0.0" xmlns:xsi&#61;"http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation&#61;"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.3.4.RELEASEversion><relativePath/> parent><groupId>com.examplegroupId><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-starterartifactId>dependency><dependency><groupId>org.projectlombokgroupId><artifactId>lombokartifactId><optional>trueoptional>dependency><dependency><groupId>org.slf4jgroupId><artifactId>slf4j-apiartifactId><version>1.7.25version>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>org.springframework.bootgroupId><artifactId>spring-boot-starter-quartzartifactId>dependency><dependency><groupId>mysqlgroupId><artifactId>mysql-connector-javaartifactId><version>5.1.48version>dependency><dependency><groupId>com.zaxxergroupId><artifactId>HikariCPartifactId><version>2.7.9version>dependency><dependency><groupId>org.mybatis.spring.bootgroupId><artifactId>mybatis-spring-boot-starterartifactId><version>1.3.1version>dependency>
project>

2、application.yml配置

logging:file:name: slf4j-testpath: ./logsmax-size: 10MBlevel:root: infoconfig: classpath:logback-gnete.xmlspring:datasource:driver-class-name: com.mysql.jdbc.Drivername: mybatispassword: 123456url: jdbc:mysql://127.0.0.1:3306/mybatis?useUnicode&#61;true&characterEncoding&#61;utf-8&useSSL&#61;false&allowMultiQueries&#61;true&autoReconnect&#61;true&failOverReadOnly&#61;falseusername: roottype: com.zaxxer.hikari.HikariDataSourcehikari:minimum-idle: 100maximum-pool-size: 500auto-commit: trueidle-timeout: 30000pool-name: DatebookHikariCPmax-lifetime: 1800000connection-timeout: 30000validation-timeout: 3000quartz:job-store-type: jdbc # Job 存储器类型。默认为 memory 表示内存&#xff0c;可选 jdbc 使用数据库。jdbc:initialize-schema: alwaysproperties:org:quartz:scheduler:instanceName: AiCloudwalkSmpcGneteSchedulerinstanceId: AUTOjobStore:class: org.quartz.impl.jdbcjobstore.JobStoreTX # JobStore 实现类driverDelegateClass: org.quartz.impl.jdbcjobstore.StdJDBCDelegatetablePrefix: QRTZ_ # Quartz 表前缀isClustered: true # 是集群模式clusterCheckinInterval: 10000useProperties: falsedataSource: quartzDataSource # 使用的数据源dataSource:quartzDataSource:driver: com.mysql.jdbc.DriverURL: jdbc:mysql://127.0.0.1:3306/mybatis?useUnicode&#61;true&characterEncoding&#61;utf-8&useSSL&#61;false&allowMultiQueries&#61;trueuser: rootpassword: 123456provider: hikaricpthreadPool:class: org.quartz.simpl.SimpleThreadPoolthreadCount: 10 # 线程池大小&#xff0c;默认为10threadPriority: 5 # 线程优先级threadsInheritContextClassLoaderOfInitializingThread: truemessages:basename: messages_zhcrons:quartzJobFirst: 0/5 * * * * ?#mybatis
mybatis:mapper-locations: classpath*:mybatis/mysql/*.xmltype-aliases-package: com.example.demo.entity

crons表达式的在线生成网站&#xff1a;http://www.bejson.com/othertools/cron/。

更多Quartz Scheduler 附加属性&#xff0c;可以看 http://www.quartz-scheduler.org/documentation/2.4.0-SNAPSHOT/configuration.html


3、自定义AbstractQuartzConfig类

package com.example.demo.configs;import org.quartz.*;public abstract class AbstractQuartzConfig {private String name &#61; null;protected JobDetail job(Class <? extends Job> clazz){this.name &#61; clazz.getSimpleName();return JobBuilder.newJob().ofType(clazz).withIdentity(name).storeDurably() // 没有 Trigger 关联的时候任务是否被保留。因为创建 JobDetail 时&#xff0c;还没 Trigger 指向它&#xff0c;所以需要设置为 true &#xff0c;表示保留。.build();}protected Trigger triggerJob(String cros, JobDetail jobDetail){return TriggerBuilder.newTrigger().forJob(jobDetail) // 对应 Job 为 jobDetail.withIdentity("triggerFor".concat(this.name)) // 名字为 triggerFor*.startNow() //立即启动.withSchedule(CronScheduleBuilder.cronSchedule(cros).withMisfireHandlingInstructionDoNothing()).build();}
}

4、自定义的QuartzConfig类

package com.example.demo.configs;import com.example.demo.job.QuartzJobFirst;
import org.quartz.JobDetail;
import org.quartz.Trigger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;&#64;Configuration
public class QuartzConfig extends AbstractQuartzConfig{&#64;Value("${crons.quartzJobFirst}")private String cros;&#64;Beanpublic JobDetail jobTest(){return super.job(QuartzJobFirst.class);}&#64;Beanpublic Trigger triggerJobTest(){return super.triggerJob(cros,this.jobTest());}
}

传入yml文件中定义的crons。

使用&#64;Bean自动设置。也可以手动设置。


5、创建QuartzJobFirst定时任务

package com.example.demo.job;import lombok.extern.slf4j.Slf4j;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;&#64;Slf4j
&#64;DisallowConcurrentExecution
public class QuartzJobFirst extends QuartzJobBean {&#64;Overrideprotected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {log.info("————————————定时任务正在运行————————————");}
}

6、Application类

package com.example.demo;import lombok.extern.slf4j.Slf4j;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;&#64;SpringBootApplication
&#64;Slf4j
&#64;MapperScan({"com.example.demo.**.mapper"})
public class DemoApplication {public static void main(String[] args) {SpringApplication.run(DemoApplication.class, args);}}

7、项目结构

如图&#xff1a;


image-20201021195743220

8、运行结果

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-pp3qJacC-1603282687243)(https://raw.githubusercontent.com/188xuhe/images/master/image-20201021195834667.png)]

定时相关的表&#xff1a;

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-uIpNxFcU-1603282687245)(https://raw.githubusercontent.com/188xuhe/images/master/image-20201021201704970.png)]


推荐阅读
author-avatar
手机用户2502906401
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有