当前位置:   article > 正文

从0到1搭建SpringBoot整合Quartz定时任务框架(保姆级教学+Gitee源码)_springboot 定时任务框架

springboot 定时任务框架

前言:这边我自己从0到1搭建了一套简化版的Quartz定时任务纯后端框架,把搭建的整个过程中的逻辑都在这篇博客写下来了,用于开源分享,干货满满!

目录

一、Quartz简介

二、项目整体结构图

三、代码实现

3.1、导入pom.xml依赖

3.2、ScheduleConstants常量类 

3.3、SysJob实体类

3.4、SpringUtils工具类

3.5、核心配置类

3.5.1、JobExecuteUtils执行定时任务方法类

3.5.2、AbstractQuartzJob抽象类

3.5.3、QuartzJobExecution/QuartzDisallowConcurrentExecution开启/禁止并发执行任务类

3.5.4、ScheduleUtils定时任务工具类

3.5.5、SysJobService定时任务调度信息接口

3.5.6、SysJobServiceImpl定时任务调度信息接口实现类

四、运行测试

4.1、撰写任务一

4.2、撰写任务二 

4.3、启动

五、Gitee源码地址

六、总结 


一、Quartz简介

Quartz是一个完全由Java编写的开源作业调度框架,在Java应用程序中进行作业调度提供了强大功能,以下是Quartz的四个核心概念。

1、Job(接口):它只有一个execute方法需要被重写,重写的内容就是咱们需要执行的具体内容。

2、JobDetail(调度信息):表示一个具体的可执行的调度程序,Job是这个可执行调度程序中所需要执行的具体内容,另外JobDetail还包含了这个任务的调度方案和策略。

3、Trigger(触发器):代表一个调度参数的配置,动态去执行咱们的定时任务。

4、Scheduler(任务调度器):Scheduler就是任务调度控制器,需要把JobDetail和Trigger注册到Schedule中,才可以执行。

咱们废话不多说,直接上代码!

二、项目整体结构图

这边我先把我整个从0到1搭建好的框架先展示出来。

三、代码实现

下面我会详细阐述这个项目是如何完整的一步步搭建起来的。

3.1、导入pom.xml依赖

  1. <dependencies>
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter-web</artifactId>
  5. </dependency>
  6. <!--quartz定时任务依赖 -->
  7. <dependency>
  8. <groupId>org.springframework.boot</groupId>
  9. <artifactId>spring-boot-starter-quartz</artifactId>
  10. </dependency>
  11. <!--常用工具类 -->
  12. <dependency>
  13. <groupId>org.apache.commons</groupId>
  14. <artifactId>commons-lang3</artifactId>
  15. </dependency>
  16. <!--lombok依赖 -->
  17. <dependency>
  18. <groupId>org.projectlombok</groupId>
  19. <artifactId>lombok</artifactId>
  20. <optional>true</optional>
  21. </dependency>
  22. <dependency>
  23. <groupId>org.springframework.boot</groupId>
  24. <artifactId>spring-boot-starter-test</artifactId>
  25. <scope>test</scope>
  26. </dependency>
  27. </dependencies>

3.2、ScheduleConstants常量类 

Misfire解释:周期性任务需要在某个规定的时间执行,但是由于某种原因导致任务未执行,称为MisFire。

这边主要定义了五种常量:

1、TASK_PARAMS:用于存放和获取定时任务参数的KEY值。

2、MISFIRE_DEFAULT(默认):等价于MISFIRE_FIRE_AND_PROCEED

3、MISFIRE_IGNORE_MISFIRES(立即执行):错过多少次,初次执行的时候,所有未触发的都会一次性立即执行,然后按照原规律进行正常后续调度。
4、MISFIRE_FIRE_AND_PROCEED(执行一次):无论错过多少次,初次运行的时候,立即执行第一个错过的并丢弃其他的,后续的执行仍按照原规律进行执行。
5、MISFIRE_DO_NOTHING(放弃执行):无论错过多少次,均忽略,后续的执行仍按照原规律进行执行。

三种执行策略详解:

假设有个任务从9点开始,每隔一个小时就会执行。

立即执行(withMisfireHandlingInstructionIgnoreMisfires):所有misfire的任务会马上执行,如果9点misfire了,在10:15系统恢复之后,9点,10点的misfire会马上执行,然后执行下一个周期的任务。

执行一次(WithMisfireHandlingInstructionFireAndProceed):会合并部分的misfire,正常执行下一个周期的任务,假设9,10的任务都misfire了,系统在10:15分起来了。只会执行9点的misfire,10点的misfire被丢弃,下次正点执行任务。

放弃执行(withMisfireHandlingInstructionDoNothing):所有的misfire不管,执行下一个周期的任务。

  1. package com.ithuang.quartz.constant;
  2. /**
  3. * 常量
  4. * @author HTT
  5. */
  6. public class ScheduleConstants
  7. {
  8. /**
  9. * 参数
  10. */
  11. public static final String TASK_PARAMS = "PARAMS";
  12. /** 默认 */
  13. public static final String MISFIRE_DEFAULT = "0";
  14. /**
  15. * 忽略错过的执行,按新 Cron 继续运行。
  16. */
  17. public static final String MISFIRE_IGNORE_MISFIRES = "1";
  18. /**
  19. * 补偿错过的执行,然后继续运行。
  20. */
  21. public static final String MISFIRE_FIRE_AND_PROCEED = "2";
  22. /**
  23. * 错过的执行不做任何处理,等待下一次 Cron 触发。
  24. */
  25. public static final String MISFIRE_DO_NOTHING = "3";
  26. }

3.3、SysJob实体类

这边我只列举了一些必须会用到的字段,其他字段可以根据实际需求来进行扩展。

  1. package com.ithuang.quartz.domain;
  2. import com.ithuang.quartz.constant.ScheduleConstants;
  3. import lombok.Data;
  4. /**
  5. * 定时任务调度表 sys_job
  6. *
  7. * @author HTT
  8. */
  9. @Data
  10. public class SysJob
  11. {
  12. /**
  13. * 定时任务ID
  14. */
  15. private String jobId;
  16. /**
  17. * 定时任务名称
  18. */
  19. private String jobName;
  20. /**
  21. * 定时任务组
  22. */
  23. private String jobGroup;
  24. /**
  25. * 目标bean名
  26. */
  27. private String beanTarget;
  28. /**
  29. * 目标bean的方法名
  30. */
  31. private String beanMethodTarget;
  32. /**
  33. * 执行表达式
  34. */
  35. private String cronExpression;
  36. /**
  37. * 是否并发
  38. * 0代表允许并发执行
  39. * 1代表不允许并发执行
  40. */
  41. private String concurrent;
  42. /**
  43. * 计划策略
  44. */
  45. private String misfirePolicy = ScheduleConstants.MISFIRE_DEFAULT;
  46. }

3.4、SpringUtils工具类

1、实现BeanFactoryPostProcessor接口,重写postProcessBeanFactory()方法,在所有Bean初始化之前就会被执行,因此可以在此处获取到最主要的BeanFactory。

2、通过beanFactory对象提供的API实现获取 Bean功能。

  1. package com.ithuang.quartz.utils;
  2. import org.springframework.aop.framework.AopContext;
  3. import org.springframework.beans.BeansException;
  4. import org.springframework.beans.factory.NoSuchBeanDefinitionException;
  5. import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
  6. import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
  7. import org.springframework.context.ApplicationContext;
  8. import org.springframework.context.ApplicationContextAware;
  9. import org.springframework.stereotype.Component;
  10. /**
  11. * 获取Bean的工具类
  12. * @author HTT
  13. */
  14. @Component
  15. public final class SpringUtils implements BeanFactoryPostProcessor
  16. {
  17. /** Spring应用上下文环境 */
  18. private static ConfigurableListableBeanFactory beanFactory;
  19. @Override
  20. public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException
  21. {
  22. SpringUtils.beanFactory = beanFactory;
  23. }
  24. /**
  25. * 获取对象
  26. *
  27. * @param name
  28. * @return Object 一个以所给名字注册的bean的实例
  29. * @throws BeansException
  30. *
  31. */
  32. @SuppressWarnings("unchecked")
  33. public static <T> T getBean(String name) throws BeansException
  34. {
  35. return (T) beanFactory.getBean(name);
  36. }
  37. }

3.5、核心配置类

在讲解之前,我先简单梳理一些每个实体类的大致作用,以及它们之间的联系和执行逻辑。

1、JobExecuteUtils:任务执行的工具类,通过反射调用目标Bean的方法。

2、AbstractQuartzJob:抽象QuartzJob类,实现了execute方法,在执行任务前后做了trycatch。

3、QuartzJobExecution:任务执行类,继承AbstractQuartzJob,在doExecute方法中调用JobExecuteUtils、executeMethod执行目标方法。

4、QuartzDisallowConcurrentExecution:禁止并发执行的任务执行类,也继承自AbstractQuartzJob,执行逻辑同QuartzJobExecution。

5、ScheduleUtils:任务调度的工具类,根据SysJob创建JobDetail和CronTrigger,调度任务。

6、SysJobService:任务管理业务接口,定义了初始化、增加、修改、删除任务等方法。

7、SysJobServiceImpl:任务管理业务接口实现类。

执行逻辑:

1、初始化时,SysJobServiceImpl从数据库加载定时任务,调度到调度器。

2、调度器根据CronTrigger触发时间启动JobDetail。

3、JobDetail执行时调用对应Job类的execute方法。

4、AbstractQuartzJob实现了execute方法,在其中调用子类doExecute。

5、子类QuartzJobExecution的doExecute通过JobExecuteUtils反射执行目标方法。

6、这样就完成了定时任务的执行。

3.5.1、JobExecuteUtils执行定时任务方法类

1、我们通过jobExecutionContext.getMergedJobDataMap().get(TASK_PARAMS);这个方法去获取咱们的SysJob参数信息。

2、默认获取的是Object类型,所以我们需要通过BeanUtils.copyProperties(param,sysJob);这个方法进行实体类的转换和拷贝,注意参数顺序别写反了。

3、然后我们通过SpringUtils封装好的getBean方法,通过拷贝好的实体类中的参数去动态进行获取被Spring托管的Bean。

4、获取到Bean之后通过bean.getClass().getMethod(sysJob.getBeanMethodTarget());这个代码去获取Bean中需要执行的方法。

5、最后通过method.invoke(bean);进行执行Bean中对应的方法内容。

  1. public static void executeMethod(JobExecutionContext jobExecutionContext) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
  2. Object param = jobExecutionContext.getMergedJobDataMap().get(TASK_PARAMS);
  3. SysJob sysJob = new SysJob();
  4. BeanUtils.copyProperties(param,sysJob);
  5. Object bean = SpringUtils.getBean(sysJob.getBeanTarget());
  6. Method method = bean.getClass().getMethod(sysJob.getBeanMethodTarget());
  7. method.invoke(bean);
  8. }

完整代码: 

  1. package com.ithuang.quartz.utils;
  2. import com.ithuang.quartz.domain.SysJob;
  3. import org.quartz.JobExecutionContext;
  4. import org.springframework.beans.BeanUtils;
  5. import java.lang.reflect.InvocationTargetException;
  6. import java.lang.reflect.Method;
  7. import static com.ithuang.quartz.constant.ScheduleConstants.TASK_PARAMS;
  8. /**
  9. * 执行定时任务的方法
  10. * @author HTT
  11. */
  12. public class JobExecuteUtils {
  13. /**
  14. * 获取bean并执行对应的方法
  15. * @param jobExecutionContext
  16. * @throws NoSuchMethodException
  17. * @throws InvocationTargetException
  18. * @throws IllegalAccessException
  19. */
  20. public static void executeMethod(JobExecutionContext jobExecutionContext) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
  21. Object param = jobExecutionContext.getMergedJobDataMap().get(TASK_PARAMS);
  22. SysJob sysJob = new SysJob();
  23. BeanUtils.copyProperties(param,sysJob);
  24. Object bean = SpringUtils.getBean(sysJob.getBeanTarget());
  25. Method method = bean.getClass().getMethod(sysJob.getBeanMethodTarget());
  26. method.invoke(bean);
  27. }
  28. }

3.5.2、AbstractQuartzJob抽象类

定义了一个抽象类并实现了Job接口,同时重写execute方法

  1. @Override
  2. public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
  3. try {
  4. doExecute(jobExecutionContext);
  5. } catch (Exception e) {
  6. throw new RuntimeException(e);
  7. }
  8. }

这个方法是定时任务执行的核心方法,其次在这个抽象类当中我们还定义了一个doExecute方法

    protected abstract void doExecute(JobExecutionContext jobExecutionContext) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException;

主要就是为了写我们定时任务的执行逻辑,这边巧妙的用到了Java的设计模式-模板方法模式,关于什么是模板方法模式,可以看我前几期的博客。

完整代码:

  1. package com.ithuang.quartz.domain;
  2. import org.quartz.Job;
  3. import org.quartz.JobExecutionContext;
  4. import org.quartz.JobExecutionException;
  5. import java.lang.reflect.InvocationTargetException;
  6. /**
  7. * 抽象quartz调用
  8. * 这里我采用了设计模式中的模板方法模式
  9. * @author HTT
  10. */
  11. public abstract class AbstractQuartzJob implements Job {
  12. @Override
  13. public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
  14. try {
  15. doExecute(jobExecutionContext);
  16. } catch (Exception e) {
  17. throw new RuntimeException(e);
  18. }
  19. }
  20. protected abstract void doExecute(JobExecutionContext jobExecutionContext) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException;
  21. }

3.5.3、QuartzJobExecution/QuartzDisallowConcurrentExecution开启/禁止并发执行任务类

这边我们继承了上述的抽象类,通过@DisallowConcurrentExecution这个注解来禁止咱们的定时任务的并发执行,如果不加则是默认允许并发执行,最后我们重写了doExecute方法去执行我们定时任务的处理逻辑。

例如有个定时任务每隔5秒执行一次,不过这个任务做完可能需要20秒。

允许并发执行:

在这处理的20秒钟,肯定需要处理下一个任务了,如果设置了允许并发执行,不会等到上一个任务执行完毕才会执行下一个任务,只要每隔5s就会执行下一个任务。

完整代码:

  1. package com.ithuang.quartz.domain;
  2. import com.ithuang.quartz.utils.JobExecuteUtils;
  3. import com.ithuang.quartz.utils.SpringUtils;
  4. import org.quartz.JobExecutionContext;
  5. import org.springframework.beans.BeanUtils;
  6. import java.lang.reflect.InvocationTargetException;
  7. import java.lang.reflect.Method;
  8. import static com.ithuang.quartz.utils.JobExecuteUtils.executeMethod;
  9. import static org.springframework.beans.BeanUtils.*;
  10. /**
  11. * 定时任务处理(允许并发执行)
  12. * @author HTT
  13. */
  14. public class QuartzJobExecution extends AbstractQuartzJob
  15. {
  16. @Override
  17. protected void doExecute(JobExecutionContext jobExecutionContext) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
  18. executeMethod(jobExecutionContext);
  19. }
  20. }

允许并发执行体现在任务一中。

不允许并发执行(@DisallowConcurrentExecution):

在这处理的20秒钟,肯定需要处理下一个任务了,如果设置了不允许并发执行,会必须等到上一个任务执行完毕才会执行下一个任务。

完整代码:

  1. package com.ithuang.quartz.domain;
  2. import com.ithuang.quartz.utils.SpringUtils;
  3. import org.quartz.DisallowConcurrentExecution;
  4. import org.quartz.JobExecutionContext;
  5. import java.lang.reflect.InvocationTargetException;
  6. import java.lang.reflect.Method;
  7. import static com.ithuang.quartz.utils.JobExecuteUtils.executeMethod;
  8. /**
  9. * 定时任务处理(禁止并发执行)
  10. * @author HTT
  11. */
  12. @DisallowConcurrentExecution
  13. public class QuartzDisallowConcurrentExecution extends AbstractQuartzJob
  14. {
  15. @Override
  16. protected void doExecute(JobExecutionContext jobExecutionContext) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
  17. executeMethod(jobExecutionContext);
  18. }
  19. }

不允许并发执行体现在任务二中。

3.5.4、ScheduleUtils定时任务工具类

这边我一共封装了三个方法,

getQuartzJobClass这个方法是主要通过SysJob实体类当中会通过动态参数获取任务类并决定当前任务是否并发执行(0代表并发执行,1代表禁止并发执行)。

  1. private static Class<? extends Job> getQuartzJobClass(SysJob sysJob)
  2. {
  3. boolean isConcurrent = "0".equals(sysJob.getConcurrent());
  4. return isConcurrent ? QuartzJobExecution.class : QuartzDisallowConcurrentExecution.class;
  5. }

handleCronScheduleMisfirePolicy这个方法主要设置待执行任务的执行策略。

  1. public static CronScheduleBuilder handleCronScheduleMisfirePolicy(SysJob job, CronScheduleBuilder cb) {
  2. switch (job.getMisfirePolicy())
  3. {
  4. case ScheduleConstants.MISFIRE_DEFAULT:
  5. return cb;
  6. case ScheduleConstants.MISFIRE_IGNORE_MISFIRES:
  7. return cb.withMisfireHandlingInstructionIgnoreMisfires();
  8. case ScheduleConstants.MISFIRE_FIRE_AND_PROCEED:
  9. return cb.withMisfireHandlingInstructionFireAndProceed();
  10. case ScheduleConstants.MISFIRE_DO_NOTHING:
  11. return cb.withMisfireHandlingInstructionDoNothing();
  12. default:
  13. throw new RuntimeException("策略异常");
  14. }
  15. }

createScheduleJob方法也就是我们最主要的方法了,它的逻辑总共7个步骤如下:

1、得到任务类(是否并发执行)

2、构建job信息

3、构件表达式调度构建器

4、配置执行策略

5、按新的cronExpression表达式构建一个新的trigger

6、放入参数,运行时的方法可以获取

7、执行调度任务

  1. public static void createScheduleJob(Scheduler scheduler, SysJob job) throws SchedulerException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
  2. //获取任务类型
  3. Class<? extends Job> jobClass = getQuartzJobClass(job);
  4. // 构建job信息
  5. String cornExpression = job.getCronExpression();
  6. JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(job.getJobId(),job.getJobGroup()).build();
  7. // 表达式调度构建器
  8. CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(cornExpression);
  9. //配置执行策略
  10. cronScheduleBuilder = handleCronScheduleMisfirePolicy(job,cronScheduleBuilder);
  11. // 按新的cronExpression表达式构建一个新的trigger
  12. CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(job.getJobId(),job.getJobGroup())
  13. .withSchedule(cronScheduleBuilder).build();
  14. // 放入参数,运行时的方法可以获取
  15. jobDetail.getJobDataMap().put(TASK_PARAMS, job);
  16. // 执行调度任务
  17. scheduler.scheduleJob(jobDetail, trigger);
  18. }

完整代码: 

  1. package com.ithuang.quartz.utils;
  2. import com.ithuang.quartz.constant.ScheduleConstants;
  3. import com.ithuang.quartz.domain.QuartzDisallowConcurrentExecution;
  4. import com.ithuang.quartz.domain.QuartzJobExecution;
  5. import com.ithuang.quartz.domain.SysJob;
  6. import org.quartz.*;
  7. import org.springframework.stereotype.Component;
  8. import java.lang.reflect.InvocationTargetException;
  9. import static com.ithuang.quartz.constant.ScheduleConstants.TASK_PARAMS;
  10. /**
  11. * 定时任务工具类
  12. * @author HTT
  13. */
  14. @Component
  15. public class ScheduleUtils {
  16. /**
  17. * 得到quartz任务类
  18. *
  19. * @param sysJob 执行计划
  20. * @return 具体执行任务类
  21. */
  22. private static Class<? extends Job> getQuartzJobClass(SysJob sysJob)
  23. {
  24. boolean isConcurrent = "0".equals(sysJob.getConcurrent());
  25. return isConcurrent ? QuartzJobExecution.class : QuartzDisallowConcurrentExecution.class;
  26. }
  27. /**
  28. * 创建定时任务
  29. */
  30. public static void createScheduleJob(Scheduler scheduler, SysJob job) throws SchedulerException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
  31. //获取任务类型
  32. Class<? extends Job> jobClass = getQuartzJobClass(job);
  33. // 构建job信息
  34. String cornExpression = job.getCronExpression();
  35. JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(job.getJobId(),job.getJobGroup()).build();
  36. // 表达式调度构建器
  37. CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(cornExpression);
  38. //配置执行策略
  39. cronScheduleBuilder = handleCronScheduleMisfirePolicy(job,cronScheduleBuilder);
  40. // 按新的cronExpression表达式构建一个新的trigger
  41. CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(job.getJobId(),job.getJobGroup())
  42. .withSchedule(cronScheduleBuilder).build();
  43. // 放入参数,运行时的方法可以获取
  44. jobDetail.getJobDataMap().put(TASK_PARAMS, job);
  45. // 执行调度任务
  46. scheduler.scheduleJob(jobDetail, trigger);
  47. }
  48. /**
  49. * 设置定时任务策略
  50. */
  51. public static CronScheduleBuilder handleCronScheduleMisfirePolicy(SysJob job, CronScheduleBuilder cb) {
  52. switch (job.getMisfirePolicy())
  53. {
  54. case ScheduleConstants.MISFIRE_DEFAULT:
  55. return cb;
  56. case ScheduleConstants.MISFIRE_IGNORE_MISFIRES:
  57. return cb.withMisfireHandlingInstructionIgnoreMisfires();
  58. case ScheduleConstants.MISFIRE_FIRE_AND_PROCEED:
  59. return cb.withMisfireHandlingInstructionFireAndProceed();
  60. case ScheduleConstants.MISFIRE_DO_NOTHING:
  61. return cb.withMisfireHandlingInstructionDoNothing();
  62. default:
  63. throw new RuntimeException("策略异常");
  64. }
  65. }
  66. }

3.5.5、SysJobService定时任务调度信息接口

撰写定时任务调度的接口,主要分为初始化所有任务、新增任务,立即执行任务、更新任务、暂停任务,恢复任务和删除任务,代码如下,这个不多说,主要详细讲解一下它的实现类。

  1. package com.ithuang.quartz.service;
  2. import com.ithuang.quartz.domain.SysJob;
  3. import org.quartz.SchedulerException;
  4. import java.lang.reflect.InvocationTargetException;
  5. /**
  6. * 定时任务调度信息
  7. * @author HTT
  8. */
  9. public interface SysJobService {
  10. /**
  11. * 项目启动时,初始化定时器
  12. */
  13. void init() throws SchedulerException, NoSuchMethodException, InvocationTargetException, IllegalAccessException;
  14. /**
  15. * 新增任务
  16. *
  17. * @param job 调度信息
  18. * @return 结果
  19. */
  20. public int insertJob(SysJob job) throws SchedulerException, InvocationTargetException, NoSuchMethodException, IllegalAccessException;
  21. /**
  22. * 立即运行任务
  23. *
  24. * @param job 调度信息
  25. * @return 结果
  26. */
  27. public void run(SysJob job) throws SchedulerException;
  28. /**
  29. * 更新任务
  30. *
  31. * @param job 调度信息
  32. * @return 结果
  33. */
  34. public int updateJob(SysJob job) throws SchedulerException, InvocationTargetException, NoSuchMethodException, IllegalAccessException;
  35. /**
  36. * 暂停任务
  37. *
  38. * @param job 调度信息
  39. * @return 结果
  40. */
  41. public int pauseJob(SysJob job) throws SchedulerException;
  42. /**
  43. * 恢复任务
  44. *
  45. * @param job 调度信息
  46. * @return 结果
  47. */
  48. public int resumeJob(SysJob job) throws SchedulerException;
  49. /**
  50. * 删除任务后,所对应的trigger也将被删除
  51. *
  52. * @param job 调度信息
  53. * @return 结果
  54. */
  55. public int deleteJob(SysJob job) throws SchedulerException;
  56. }

3.5.6、SysJobServiceImpl定时任务调度信息接口实现类

1、首先initTaskList这个方法我这边做了偷懒,直接写了一个List集合在项目中,正确的配置应该是从数据库去查询一共有哪些定时任务需要程序去执行的,以及对应的配置信息应该如何去执行。

  1. public List<SysJob> initTaskList(){
  2. List<SysJob> list = new ArrayList<>();
  3. SysJob job = new SysJob();
  4. job.setJobId(UUID.randomUUID().toString());
  5. job.setJobGroup("system");
  6. job.setConcurrent("0");
  7. job.setCronExpression("0/5 * * * * ?");
  8. job.setBeanTarget("task1");
  9. job.setBeanMethodTarget("handle");
  10. list.add(job);
  11. job = new SysJob();
  12. job.setJobId(UUID.randomUUID().toString());
  13. job.setJobGroup("system");
  14. job.setConcurrent("1");
  15. job.setCronExpression("0/50 * * * * ?");
  16. job.setBeanTarget("task2");
  17. job.setBeanMethodTarget("handle");
  18. job.setMisfirePolicy(MISFIRE_IGNORE_MISFIRES);
  19. list.add(job);
  20. return list;
  21. }

2、其次在init方法中,@PostConstruct这个注解会在项目启动的时候帮我们进行初始化,其次我调用了clear方法进行先清空定时任务,使用循环获取到需要所有定时任务集合,通过createScheduleJob方法去创建。

  1. @Resource
  2. private Scheduler scheduler;
  3. @PostConstruct
  4. @Override
  5. public void init() throws SchedulerException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
  6. scheduler.clear();
  7. List<SysJob> list = initTaskList();
  8. for (int i = 0 ; i < list.size() ; i ++){
  9. SysJob job = list.get(i);
  10. ScheduleUtils.createScheduleJob(scheduler, job);
  11. }
  12. }

完整代码: 

  1. package com.ithuang.quartz.service.impl;
  2. import com.ithuang.quartz.domain.SysJob;
  3. import com.ithuang.quartz.service.SysJobService;
  4. import com.ithuang.quartz.utils.ScheduleUtils;
  5. import org.quartz.JobKey;
  6. import org.quartz.Scheduler;
  7. import org.quartz.SchedulerException;
  8. import org.springframework.stereotype.Service;
  9. import javax.annotation.PostConstruct;
  10. import javax.annotation.Resource;
  11. import java.lang.reflect.InvocationTargetException;
  12. import java.util.ArrayList;
  13. import java.util.List;
  14. import java.util.UUID;
  15. import static com.ithuang.quartz.constant.ScheduleConstants.MISFIRE_IGNORE_MISFIRES;
  16. /**
  17. * 定时任务调度服务
  18. * @author HTT
  19. */
  20. @Service
  21. public class SysJobServiceImpl implements SysJobService {
  22. @Resource
  23. private Scheduler scheduler;
  24. /**
  25. * 模拟从数据库获取数据,这边偷懒了
  26. * @return
  27. */
  28. public List<SysJob> initTaskList(){
  29. List<SysJob> list = new ArrayList<>();
  30. SysJob job = new SysJob();
  31. job.setJobId(UUID.randomUUID().toString());
  32. job.setJobGroup("system");
  33. job.setConcurrent("0");
  34. job.setCronExpression("0/5 * * * * ?");
  35. job.setBeanTarget("task1");
  36. job.setBeanMethodTarget("handle");
  37. list.add(job);
  38. job = new SysJob();
  39. job.setJobId(UUID.randomUUID().toString());
  40. job.setJobGroup("system");
  41. job.setConcurrent("1");
  42. job.setCronExpression("0/50 * * * * ?");
  43. job.setBeanTarget("task2");
  44. job.setBeanMethodTarget("handle");
  45. job.setMisfirePolicy(MISFIRE_IGNORE_MISFIRES);
  46. list.add(job);
  47. return list;
  48. }
  49. /**
  50. * 初始化定时任务
  51. * @throws SchedulerException
  52. * @throws NoSuchMethodException
  53. * @throws InvocationTargetException
  54. * @throws IllegalAccessException
  55. */
  56. @PostConstruct
  57. @Override
  58. public void init() throws SchedulerException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
  59. scheduler.clear();
  60. List<SysJob> list = initTaskList();
  61. for (int i = 0 ; i < list.size() ; i ++){
  62. SysJob job = list.get(i);
  63. ScheduleUtils.createScheduleJob(scheduler, job);
  64. }
  65. }
  66. @Override
  67. public int insertJob(SysJob job) throws SchedulerException, InvocationTargetException, NoSuchMethodException, IllegalAccessException {
  68. ScheduleUtils.createScheduleJob(scheduler, job);
  69. return 1;
  70. }
  71. @Override
  72. public void run(SysJob job) throws SchedulerException {
  73. scheduler.triggerJob(JobKey.jobKey(job.getJobId(),job.getJobGroup()));
  74. }
  75. @Override
  76. public int updateJob(SysJob job) throws SchedulerException, InvocationTargetException, NoSuchMethodException, IllegalAccessException {
  77. // 判断是否存在
  78. JobKey jobKey = JobKey.jobKey(job.getJobId(),job.getJobGroup());
  79. if (scheduler.checkExists(jobKey)) {
  80. scheduler.deleteJob(jobKey);
  81. }
  82. ScheduleUtils.createScheduleJob(scheduler, job);
  83. return 1;
  84. }
  85. @Override
  86. public int pauseJob(SysJob job) throws SchedulerException {
  87. scheduler.pauseJob(JobKey.jobKey(job.getJobId(),job.getJobGroup()));
  88. return 1;
  89. }
  90. @Override
  91. public int resumeJob(SysJob job) throws SchedulerException {
  92. scheduler.resumeJob(JobKey.jobKey(job.getJobId(),job.getJobGroup()));
  93. return 1;
  94. }
  95. @Override
  96. public int deleteJob(SysJob job) throws SchedulerException {
  97. scheduler.deleteJob(JobKey.jobKey(job.getJobId(),job.getJobGroup()));
  98. return 1;
  99. }
  100. }

四、运行测试

以上就是整个定时任务框架实现的核心逻辑,这边我们直接运行测试一下.

4.1、撰写任务一

task1就是我们任务一Bean的名称,handle就是任务二需要执行的具体方法。

  1. package com.ithuang.quartz.task;
  2. import org.springframework.stereotype.Component;
  3. import java.util.Date;
  4. @Component("task1")
  5. public class Task1 {
  6. public void handle() throws InterruptedException {
  7. Date date = new Date();
  8. System.out.println("task1"+date+"开始");
  9. Thread.sleep(10000);
  10. System.out.println("task1"+date+"结束");
  11. }
  12. }

4.2、撰写任务二 

task2就是我们任务二Bean的名称,handle就是任务二需要执行的具体方法。

  1. package com.ithuang.quartz.task;
  2. import org.springframework.stereotype.Component;
  3. import java.util.Date;
  4. @Component("task2")
  5. public class Task2 {
  6. public void handle(){
  7. Date date = new Date();
  8. System.out.println("task2"+date+"开始");
  9. try {
  10. Thread.sleep(1000);
  11. } catch (InterruptedException e) {
  12. throw new RuntimeException(e);
  13. }
  14. System.out.println("task2"+date+"结束");
  15. }
  16. }

4.3、启动

这边我默认采用并发执行了,反正参数都可以动态进行配置 。

这是不采用并发执行的效果。

代码运行成功! 

五、Gitee源码地址

SpringBoot整合Quartz定时任务框架

六、总结 

这边就是我自己从0到1搭建了一个比较成熟的定时任务框架,参考的是目前主流的若依框架,我在他的框架上做了一些简化,不过也能应付大部分的场景了,非常的方便,功能也非常完善,整个项目的源码已经全部吃透,这边做一个总结,收获满满!

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号