在网上查询资料,写写删删六七遍还是没怎么搞懂,最后还是写出来了,总结一下,确定是最简单的了。

前言

为什么要使用quartz,而不用springboot的@Scheduled?

因为在日常的业务中,需要经常变换任务的执行时间,即cron的表达式,所以对于@Scheduled用来操作就有些麻烦了,而quartz就很好的可以封装成一个可修改的调用接口,方便业务的多变性


文章导航

  • 前言
  • springboot使用quartz执行任务
    • 思路
    • 添加POM依赖
    • 1. 任务调度器
    • 2. 需要执行的业务任务
    • 3. 启动项目时将quartz也启动
    • cron表达式生成工具类
    • 测试代码

springboot使用quartz执行任务


思路

为什么要说一下思路,因为这个执行的顺序把我搞得很懵,所以只需要将这个思路搞清楚,就很容易的使用quartz的功能了,我简单描述一下我的这个思路

  • 为业务层(eg: service)封装调用quartz的方法,该方法暴露执行的cron表达式(即第一步)

  • 将业务层需要执行的作业放到quartz的执行方法中(即第二步)

  • springboot集成quartz,将quartz任务调度器跟随项目启动而启动起来(即第三步)

    思路理顺了,业务的代码也就知道在哪里写了。


添加POM依赖

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope>
</dependency>
<dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId>
</dependency>
<dependency><groupId>org.quartz-scheduler</groupId><artifactId>quartz</artifactId>
</dependency>
<dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version>
</dependency>

1. 任务调度器

在业务层可以调用这个调度器,使用spring的注入@Autowired

package com.example.springboothtml.scheduler;import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;/*** 调度器使用** @author jiaohongtao* @version 1.0* @since 2020年11月04日*/
@Slf4j
@Component
public class QuartzScheduler {private static final String JOB_NAME = "inspect_report";private static final String JOB_GROUP = "inspect_report_group";private static final String TRIGGER_NAME = "inspect_report";private static final String TRIGGER_GROUP = "inspect_report_group";private static final String JOB_TASK_ID = "job_task_id";/*** quartz任务调度器*/@Autowiredprivate Scheduler scheduler;/*** 开始执行所有任务,并开启调度器** @throws SchedulerException SchedulerException*/public void startJob() throws SchedulerException {// 这里可以放一些初始化的任务,例如服务器宕机后,需要重新启动,如果没有不用考虑这个// 步骤:1.创建一个新的 SchedulerJob 作业类,即第二步的代码// 2.在这个类里写一个方法(invoke())调用新SchedulerJob的作业,然后将方法放到这里scheduler.start();}public void add(int i, String cron) throws SchedulerException {// 构建传递参数JobDataMap jobDataMap = new JobDataMap();jobDataMap.put(JOB_TASK_ID, id);jobDataMap.put("userId", userId);JobDetail jobDetail = JobBuilder.newJob(InspectReportSchedulerJob.class).usingJobData(jobDataMap).withIdentity(JOB_NAME + id, JOB_GROUP).build();// 每5s执行一次// String cron = "*/5 * * * * ?";CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cron);CronTrigger cronTrigger = TriggerBuilder.newTrigger().withIdentity(TRIGGER_NAME + i, TRIGGER_GROUP).withSchedule(scheduleBuilder).build();scheduler.scheduleJob(jobDetail, cronTrigger);}public void remove(int i) throws SchedulerException {boolean deleteJob = scheduler.deleteJob(new JobKey(JOB_NAME + i, JOB_GROUP));log.info(deleteJob ? "任务移除成功" : "任务移除失败");}/*** 初始注入scheduler** @return scheduler* @throws SchedulerException SchedulerException*/@Beanpublic Scheduler scheduler() throws SchedulerException {SchedulerFactory schedulerFactoryBean = new StdSchedulerFactory();return schedulerFactoryBean.getScheduler();}
}

2. 需要执行的业务任务

将需要执行的业务放在放在execute方法中

package com.example.springboothtml.scheduler;import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;import java.util.Date;/*** @author jiaohongtao* @version 1.0* @since 2020年11月04日*/
@Slf4j
public class SchedulerJob implements Job {private void before() {System.out.println("任务开始执行");}@Overridepublic void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {before();log.info(new Date() + ":我开始执行了......");// TODO 业务after();}private void after() {System.out.println("任务结束执行");}
}

3. 启动项目时将quartz也启动

这个类是在项目启动时,将quartz的任务调度器也拉起来,即第一步的里的方法 — quartzScheduler.startJob()

package com.example.springboothtml.scheduler;import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ContextRefreshedEvent;/*** 启动服务后,开启调度器** @author jiaohongtao* @version 1.0* @since 2020年11月04日*/
@Configuration
public class QuartzStartListener implements ApplicationListener<ContextRefreshedEvent> {@Autowiredprivate QuartzScheduler quartzScheduler;@Overridepublic void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {try {quartzScheduler.startJob();System.out.println("*******quartz调度器启动*******");} catch (SchedulerException e) {e.printStackTrace();}}
}

cron表达式生成工具类

package com.bocloud.inspect.service.util;import java.text.SimpleDateFormat;
import java.util.Date;/*** cron表达式生成工具类** @author jiaohongtao* @version 1.0* @since 2020年11月04日*/
public class CronUtil {/*** 生成指定格式日期字符** @param date       日期* @param dateFormat : e.g:yyyy-MM-dd HH:mm:ss* @return formatTimeStr*/public static String formatDateByPattern(Date date, String dateFormat) {dateFormat = dateFormat == null ? "yyyy-MM-dd HH:mm:ss" : dateFormat;SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);return date != null ? sdf.format(date) : null;}/*** 生成cron表达式 ss mm HH dd MM ? yyyy* convert Date to cron ,eg.  "0 06 10 15 1 ? 2014"** @param date : 时间点*/public static String getCron(Date date) {String dateFormat = "ss mm HH dd MM ? yyyy";return formatDateByPattern(date, dateFormat);}/*** 生成cron表达式 ss mm HH dd MM ?* convert Date to cron ,eg.  "0 06 10 15 1 ?"** @param date : 时间点* @param type : 类型 日/周/月*/public static String getLoopCron(Date date, String type, Integer week, Integer day) {String dateFormat = "ss mm HH";//  dd MM ?String cron = formatDateByPattern(date, dateFormat);switch (type) {case "Day":return cron + " * * ?";case "Week":return cron + " ? * " + getCurrentWeek(week);case "Month":return cron + " " + day + " * ?";default:return "false";}}/*** 获取当前星期的字符 MON TUE WED THU FRI SAT SUN** @param week : 周 1 2 3 4 5 6 7* @return 星期字符*/public static String getCurrentWeek(Integer week) {String[] weeks = {"MON", "TUE", "WED", "THU", "FRI", "SAT", "SUN"};return weeks[week - 1];}public static void main(String[] args) {Date date = new Date();String dateFormat = "ss mm HH dd MM ? yyyy";String cron = formatDateByPattern(date, dateFormat);System.out.println("原始:" + cron);String day = formatDateByPattern(date, "ss mm HH");System.out.println("日报:" + day + " * * ?");// 0 15 10 ? * MON 每周一上午10点15分// 动参为 周String week = formatDateByPattern(date, "ss mm HH");System.out.println("周报:" + week + " ? * MON");// 0 15 9 10 * ? 每月10号9点15分// 动参为 号String month = formatDateByPattern(date, "ss mm HH");System.out.println("月报:" + month + " 10 * ?");}
}

测试代码

package com.example.springboothtml;import com.example.springboothtml.scheduler.CronUtil;
import com.example.springboothtml.scheduler.QuartzScheduler;
import org.junit.Test;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;/*** @author jiaohongtao* @version 1.0* @since 2020年11月04日*/
@SpringBootTest
public class QuartzTest {@AutowiredQuartzScheduler quartzScheduler;@Testpublic void test1() {// Date date = new Date();// String time = CronUtil.formatDateByPattern(date, null);Date date = null;try {date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2020-11-04 17:25:30");} catch (ParseException e) {e.printStackTrace();}try {quartzScheduler.add(1, CronUtil.getCron(date));} catch (SchedulerException e) {e.printStackTrace();}}
}

如果有看不懂的部分,请在评论区留言

springboot集成quartz,简版-通俗易懂相关推荐

  1. SpringBoot集成Quartz(解决@Autowired空指针Null问题即依赖注入的属性为null)

    SpringBoot集成Quartz(解决@Autowired空指针Null问题即依赖注入的属性为null) 参考文章: (1)SpringBoot集成Quartz(解决@Autowired空指针Nu ...

  2. 01.基于Irises的springboot项目框架(简版)

    01.基于Irises的springboot项目框架(简版) 介绍 基于Irises搭建的springboot单体应用框架(简版),支持Mybatis-plus.sql分析与打印.swagger.kk ...

  3. java quartz 动态执行,浅谈SpringBoot集成Quartz动态定时任务

    SpringBoot自带schedule 沿用的springboot少xml配置的优良传统,本身支持表达式等多种定时任务 注意在程序启动的时候加上@EnableScheduling @Schedule ...

  4. SpringBoot集成quartz定时调度任务并通过JDBC持久化

    SpringBoot集成quartz定时调度任务并通过JDBC持久化 话不多说上干货 项目pom依赖 配置类 抽象出调度任务实体类 调度执行和调度任务更改工具类 调度配置与执行的代码完毕,下面就是对持 ...

  5. Springboot集成quartz定时任务可视化配置​​​​​​​

    转自我的个人博客:Springboot集成quartz定时任务可视化配置 使用quartz定时任务已经有一段时间了,今天记录一下Springboot 2.x集成Quartz. 1.引入quartz j ...

  6. SpringBoot集成Quartz框架

    SpringBoot集成Quartz框架 (一)集成环境: ​ Win10系统 ​ JDK版本:11.0.13 ​ SpringBoot版本:2.3.4.RELEASE ​ Quartz版本:2.3. ...

  7. SpringBoot - 集成Quartz框架:Couldn‘t acquire next trigger: Couldn‘t retrieve trigger: 不良的类型值 long : \x

    写在前面 SpringBoot 集成Quartz框架时,数据保存方式使用PostgreSQL进行数据库持久化. 报错如下: Couldn't acquire next trigger: Couldn' ...

  8. SpringBoot集成Quartz(定时任务)

    SpringBoot集成Quartz(定时任务)_鱼找水需要时间的博客-CSDN博客_springboot集成quartz

  9. 定时任务:springboot集成Quartz实现多任务多触发的动态管理

    本文主要讲解以下几个方面: 1.定时任务的定义及其常见的模式 2.springboot集成quart实例 3.中途会遇到的一些问题 一.定时任务的定义及其常见的模式 1)定时任务的定义 首先要明白的是 ...

  10. SpringBoot集成Quartz动态定时任务

    SpringBoot自带schedule 沿用的springboot少xml配置的优良传统,本身支持表达式等多种定时任务 注意在程序启动的时候加上@EnableScheduling @Schedule ...

最新文章

  1. 完整的Python 3和树莓Pi大师课 Complete Python 3 and Raspberry Pi Masterclass
  2. Rocksdb 的优秀代码(三)-- 工业级 线程池实现分享
  3. C语言网络编程:TCP编程模型
  4. 基于Ionic的项目解决跨域问题
  5. Linux LVM卷挂载
  6. opencv 和 parfor
  7. 禁用删除键退回历史记录_如何在Windows 8中删除或禁用搜索超级按钮历史记录
  8. P5496-[模板]回文自动机【PAM】
  9. 基于模板的代码生成器
  10. 实现mvcc_数据库中的引擎、事务、锁、MVCC(三)
  11. 点云 数据 (偏向于研究大小)
  12. jquery引入外部CDN,失效后则引入本地jq库
  13. 华为 eNsp ipSec vpn实验配置(1)
  14. 基于springboot小型车队管理系统毕业设计源码
  15. Javaweb新闻管理系统02
  16. Django启航(四)Django配置数据库
  17. BlackHat2017热点之数据取证与事件响应
  18. csdn简单设置字体颜色
  19. Wireshark 抓包分析 HTTP 请求、响应报文格式
  20. Maxthon广告猎手规则,简简单单屏蔽广告

热门文章

  1. 记一次守护日志导致硬盘空间告警问题
  2. 相机标定原理介绍(一)
  3. Qt::QWidget 无默认标题栏边框的拖拽修改大小方式
  4. 推荐几个机器学习的干货公众号!
  5. UEditor 百度Web编辑器 - JSP版本的使用
  6. c语言程序设计题怎么写,C语言程序设计题库1(最新整理)
  7. Delphi XE组件开发技术
  8. Python Web编程入门
  9. 《Oracle 11g数据库基础教程(第2版)》读者勘误
  10. 超简单的ubuntu下安装teamview教程