基于springboot创建的web项目整合Quartz框架

打印 上一主题 下一主题

主题 759|帖子 759|积分 2277

介绍

   Quartz是OpenSymphony开源组织在Job scheduling领域又一个开源项目,它可以与J2EE与J2SE应用程序相结合也可以单独使用。Quartz可以用来创建简单或为运行十个,百个,甚至是好几万个Jobs这样复杂的程序。Jobs可以做成标准的Java组件或EJBs。Quartz的最新版本为Quartz 2.3.2。
  

  • quartz可以在某一个有规律的时间点干某件事,是一个任务调度框架,可以被集成到java的各种应用中使用,quartz框架可以支持分布式任务处理
基于springboot创建的web项目整合Quartz框架



  • 整体代码结构

  • 导入依赖
  1.         <dependency>
  2.             <groupId>org.springframework.boot</groupId>
  3.             <artifactId>spring-boot-starter-quartz</artifactId>
  4.         </dependency>
复制代码


  • 创建quartz_demo数据库,执行tables_mysql_innodb.sql文件创建对应表,下面是文件内容
  1. #
  2. # In your Quartz properties file, you'll need to set
  3. # org.quartz.jobStore.driverDelegateClass = org.quartz.impl.jdbcjobstore.StdJDBCDelegate
  4. #
  5. #
  6. # By: Ron Cordell - roncordell
  7. #  I didn't see this anywhere, so I thought I'd post it here. This is the script from Quartz to create the tables in a MySQL database, modified to use INNODB instead of MYISAM.
  8. DROP TABLE IF EXISTS QRTZ_FIRED_TRIGGERS;
  9. DROP TABLE IF EXISTS QRTZ_PAUSED_TRIGGER_GRPS;
  10. DROP TABLE IF EXISTS QRTZ_SCHEDULER_STATE;
  11. DROP TABLE IF EXISTS QRTZ_LOCKS;
  12. DROP TABLE IF EXISTS QRTZ_SIMPLE_TRIGGERS;
  13. DROP TABLE IF EXISTS QRTZ_SIMPROP_TRIGGERS;
  14. DROP TABLE IF EXISTS QRTZ_CRON_TRIGGERS;
  15. DROP TABLE IF EXISTS QRTZ_BLOB_TRIGGERS;
  16. DROP TABLE IF EXISTS QRTZ_TRIGGERS;
  17. DROP TABLE IF EXISTS QRTZ_JOB_DETAILS;
  18. DROP TABLE IF EXISTS QRTZ_CALENDARS;
  19. CREATE TABLE QRTZ_JOB_DETAILS(
  20. SCHED_NAME VARCHAR(120) NOT NULL,
  21. JOB_NAME VARCHAR(190) NOT NULL,
  22. JOB_GROUP VARCHAR(190) NOT NULL,
  23. DESCRIPTION VARCHAR(250) NULL,
  24. JOB_CLASS_NAME VARCHAR(250) NOT NULL,
  25. IS_DURABLE VARCHAR(1) NOT NULL,
  26. IS_NONCONCURRENT VARCHAR(1) NOT NULL,
  27. IS_UPDATE_DATA VARCHAR(1) NOT NULL,
  28. REQUESTS_RECOVERY VARCHAR(1) NOT NULL,
  29. JOB_DATA BLOB NULL,
  30. PRIMARY KEY (SCHED_NAME,JOB_NAME,JOB_GROUP))
  31. ENGINE=InnoDB;
  32. CREATE TABLE QRTZ_TRIGGERS (
  33. SCHED_NAME VARCHAR(120) NOT NULL,
  34. TRIGGER_NAME VARCHAR(190) NOT NULL,
  35. TRIGGER_GROUP VARCHAR(190) NOT NULL,
  36. JOB_NAME VARCHAR(190) NOT NULL,
  37. JOB_GROUP VARCHAR(190) NOT NULL,
  38. DESCRIPTION VARCHAR(250) NULL,
  39. NEXT_FIRE_TIME BIGINT(13) NULL,
  40. PREV_FIRE_TIME BIGINT(13) NULL,
  41. PRIORITY INTEGER NULL,
  42. TRIGGER_STATE VARCHAR(16) NOT NULL,
  43. TRIGGER_TYPE VARCHAR(8) NOT NULL,
  44. START_TIME BIGINT(13) NOT NULL,
  45. END_TIME BIGINT(13) NULL,
  46. CALENDAR_NAME VARCHAR(190) NULL,
  47. MISFIRE_INSTR SMALLINT(2) NULL,
  48. JOB_DATA BLOB NULL,
  49. PRIMARY KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP),
  50. FOREIGN KEY (SCHED_NAME,JOB_NAME,JOB_GROUP)
  51. REFERENCES QRTZ_JOB_DETAILS(SCHED_NAME,JOB_NAME,JOB_GROUP))
  52. ENGINE=InnoDB;
  53. CREATE TABLE QRTZ_SIMPLE_TRIGGERS (
  54. SCHED_NAME VARCHAR(120) NOT NULL,
  55. TRIGGER_NAME VARCHAR(190) NOT NULL,
  56. TRIGGER_GROUP VARCHAR(190) NOT NULL,
  57. REPEAT_COUNT BIGINT(7) NOT NULL,
  58. REPEAT_INTERVAL BIGINT(12) NOT NULL,
  59. TIMES_TRIGGERED BIGINT(10) NOT NULL,
  60. PRIMARY KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP),
  61. FOREIGN KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP)
  62. REFERENCES QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP))
  63. ENGINE=InnoDB;
  64. CREATE TABLE QRTZ_CRON_TRIGGERS (
  65. SCHED_NAME VARCHAR(120) NOT NULL,
  66. TRIGGER_NAME VARCHAR(190) NOT NULL,
  67. TRIGGER_GROUP VARCHAR(190) NOT NULL,
  68. CRON_EXPRESSION VARCHAR(120) NOT NULL,
  69. TIME_ZONE_ID VARCHAR(80),
  70. PRIMARY KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP),
  71. FOREIGN KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP)
  72. REFERENCES QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP))
  73. ENGINE=InnoDB;
  74. CREATE TABLE QRTZ_SIMPROP_TRIGGERS
  75.   (
  76.     SCHED_NAME VARCHAR(120) NOT NULL,
  77.     TRIGGER_NAME VARCHAR(190) NOT NULL,
  78.     TRIGGER_GROUP VARCHAR(190) NOT NULL,
  79.     STR_PROP_1 VARCHAR(512) NULL,
  80.     STR_PROP_2 VARCHAR(512) NULL,
  81.     STR_PROP_3 VARCHAR(512) NULL,
  82.     INT_PROP_1 INT NULL,
  83.     INT_PROP_2 INT NULL,
  84.     LONG_PROP_1 BIGINT NULL,
  85.     LONG_PROP_2 BIGINT NULL,
  86.     DEC_PROP_1 NUMERIC(13,4) NULL,
  87.     DEC_PROP_2 NUMERIC(13,4) NULL,
  88.     BOOL_PROP_1 VARCHAR(1) NULL,
  89.     BOOL_PROP_2 VARCHAR(1) NULL,
  90.     PRIMARY KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP),
  91.     FOREIGN KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP)
  92.     REFERENCES QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP))
  93. ENGINE=InnoDB;
  94. CREATE TABLE QRTZ_BLOB_TRIGGERS (
  95. SCHED_NAME VARCHAR(120) NOT NULL,
  96. TRIGGER_NAME VARCHAR(190) NOT NULL,
  97. TRIGGER_GROUP VARCHAR(190) NOT NULL,
  98. BLOB_DATA BLOB NULL,
  99. PRIMARY KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP),
  100. INDEX (SCHED_NAME,TRIGGER_NAME, TRIGGER_GROUP),
  101. FOREIGN KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP)
  102. REFERENCES QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP))
  103. ENGINE=InnoDB;
  104. CREATE TABLE QRTZ_CALENDARS (
  105. SCHED_NAME VARCHAR(120) NOT NULL,
  106. CALENDAR_NAME VARCHAR(190) NOT NULL,
  107. CALENDAR BLOB NOT NULL,
  108. PRIMARY KEY (SCHED_NAME,CALENDAR_NAME))
  109. ENGINE=InnoDB;
  110. CREATE TABLE QRTZ_PAUSED_TRIGGER_GRPS (
  111. SCHED_NAME VARCHAR(120) NOT NULL,
  112. TRIGGER_GROUP VARCHAR(190) NOT NULL,
  113. PRIMARY KEY (SCHED_NAME,TRIGGER_GROUP))
  114. ENGINE=InnoDB;
  115. CREATE TABLE QRTZ_FIRED_TRIGGERS (
  116. SCHED_NAME VARCHAR(120) NOT NULL,
  117. ENTRY_ID VARCHAR(95) NOT NULL,
  118. TRIGGER_NAME VARCHAR(190) NOT NULL,
  119. TRIGGER_GROUP VARCHAR(190) NOT NULL,
  120. INSTANCE_NAME VARCHAR(190) NOT NULL,
  121. FIRED_TIME BIGINT(13) NOT NULL,
  122. SCHED_TIME BIGINT(13) NOT NULL,
  123. PRIORITY INTEGER NOT NULL,
  124. STATE VARCHAR(16) NOT NULL,
  125. JOB_NAME VARCHAR(190) NULL,
  126. JOB_GROUP VARCHAR(190) NULL,
  127. IS_NONCONCURRENT VARCHAR(1) NULL,
  128. REQUESTS_RECOVERY VARCHAR(1) NULL,
  129. PRIMARY KEY (SCHED_NAME,ENTRY_ID))
  130. ENGINE=InnoDB;
  131. CREATE TABLE QRTZ_SCHEDULER_STATE (
  132. SCHED_NAME VARCHAR(120) NOT NULL,
  133. INSTANCE_NAME VARCHAR(190) NOT NULL,
  134. LAST_CHECKIN_TIME BIGINT(13) NOT NULL,
  135. CHECKIN_INTERVAL BIGINT(13) NOT NULL,
  136. PRIMARY KEY (SCHED_NAME,INSTANCE_NAME))
  137. ENGINE=InnoDB;
  138. CREATE TABLE QRTZ_LOCKS (
  139. SCHED_NAME VARCHAR(120) NOT NULL,
  140. LOCK_NAME VARCHAR(40) NOT NULL,
  141. PRIMARY KEY (SCHED_NAME,LOCK_NAME))
  142. ENGINE=InnoDB;
  143. CREATE INDEX IDX_QRTZ_J_REQ_RECOVERY ON QRTZ_JOB_DETAILS(SCHED_NAME,REQUESTS_RECOVERY);
  144. CREATE INDEX IDX_QRTZ_J_GRP ON QRTZ_JOB_DETAILS(SCHED_NAME,JOB_GROUP);
  145. CREATE INDEX IDX_QRTZ_T_J ON QRTZ_TRIGGERS(SCHED_NAME,JOB_NAME,JOB_GROUP);
  146. CREATE INDEX IDX_QRTZ_T_JG ON QRTZ_TRIGGERS(SCHED_NAME,JOB_GROUP);
  147. CREATE INDEX IDX_QRTZ_T_C ON QRTZ_TRIGGERS(SCHED_NAME,CALENDAR_NAME);
  148. CREATE INDEX IDX_QRTZ_T_G ON QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_GROUP);
  149. CREATE INDEX IDX_QRTZ_T_STATE ON QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_STATE);
  150. CREATE INDEX IDX_QRTZ_T_N_STATE ON QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP,TRIGGER_STATE);
  151. CREATE INDEX IDX_QRTZ_T_N_G_STATE ON QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_GROUP,TRIGGER_STATE);
  152. CREATE INDEX IDX_QRTZ_T_NEXT_FIRE_TIME ON QRTZ_TRIGGERS(SCHED_NAME,NEXT_FIRE_TIME);
  153. CREATE INDEX IDX_QRTZ_T_NFT_ST ON QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_STATE,NEXT_FIRE_TIME);
  154. CREATE INDEX IDX_QRTZ_T_NFT_MISFIRE ON QRTZ_TRIGGERS(SCHED_NAME,MISFIRE_INSTR,NEXT_FIRE_TIME);
  155. CREATE INDEX IDX_QRTZ_T_NFT_ST_MISFIRE ON QRTZ_TRIGGERS(SCHED_NAME,MISFIRE_INSTR,NEXT_FIRE_TIME,TRIGGER_STATE);
  156. CREATE INDEX IDX_QRTZ_T_NFT_ST_MISFIRE_GRP ON QRTZ_TRIGGERS(SCHED_NAME,MISFIRE_INSTR,NEXT_FIRE_TIME,TRIGGER_GROUP,TRIGGER_STATE);
  157. CREATE INDEX IDX_QRTZ_FT_TRIG_INST_NAME ON QRTZ_FIRED_TRIGGERS(SCHED_NAME,INSTANCE_NAME);
  158. CREATE INDEX IDX_QRTZ_FT_INST_JOB_REQ_RCVRY ON QRTZ_FIRED_TRIGGERS(SCHED_NAME,INSTANCE_NAME,REQUESTS_RECOVERY);
  159. CREATE INDEX IDX_QRTZ_FT_J_G ON QRTZ_FIRED_TRIGGERS(SCHED_NAME,JOB_NAME,JOB_GROUP);
  160. CREATE INDEX IDX_QRTZ_FT_JG ON QRTZ_FIRED_TRIGGERS(SCHED_NAME,JOB_GROUP);
  161. CREATE INDEX IDX_QRTZ_FT_T_G ON QRTZ_FIRED_TRIGGERS(SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP);
  162. CREATE INDEX IDX_QRTZ_FT_TG ON QRTZ_FIRED_TRIGGERS(SCHED_NAME,TRIGGER_GROUP);
  163. commit;
复制代码


  • 配置quartz
  1. server:
  2.   port: ${PORT:12011}
  3.   servlet:
  4.     session:
  5.       timeout: 86400s # session有效期(xxx秒)
  6.       cookie:
  7.         http-only: false # 如果为true, 浏览器脚本将无法访问cookie
  8.         secure: false # 如果为true, 则仅通过https连接发送cookie, http无法携带cookie
  9.     context-path:  # 程序上下文路径配置
  10. spring:
  11.   application:
  12.     name: quartz-demo
  13.   aop:
  14.     proxy-target-class: true
  15.     auto: true
  16.   datasource:
  17.     url: jdbc:mysql://localhost:3306/quartz_demo
  18.     username: root
  19.     password: 123456
  20.     driver-class-name: com.mysql.jdbc.Driver
  21.   # 配置日期格式化
  22.   jackson:
  23.     date-format: yyyy-MM-dd HH:mm:ss  #时间戳统一转换为指定格式
  24.     time-zone: GMT+8  # 时区修改为东8区
  25.   quartz:
  26.     # 将任务等保存化到数据库
  27.     job-store-type: jdbc
  28.     # 程序结束时会等待quartz相关的内容结束
  29.     wait-for-jobs-to-complete-on-shutdown: true
  30.     # QuartzScheduler启动时更新己存在的Job,这样就不用每次修改targetObject后删除qrtz_job_details表对应记录
  31.     overwrite-existing-jobs: true
  32.     properties:
  33.       org:
  34.         quartz:
  35.           # scheduler相关
  36.           scheduler:
  37.             # scheduler的实例名
  38.             instanceName: scheduler
  39.             instanceId: AUTO
  40.           # 持久化相关
  41.           jobStore:
  42.             class: org.quartz.impl.jdbcjobstore.JobStoreTX
  43.             driverDelegateClass: org.quartz.impl.jdbcjobstore.StdJDBCDelegate
  44.             # 表示数据库中相关表是QRTZ_开头的
  45.             tablePrefix: QRTZ_
  46.             useProperties: false
  47.             # 配置集群
  48.             # 是否加入集群
  49.             isClustered: true
  50.             # 容许的最大作业延长时间
  51.             clusterCheckinInterval: 20000
  52.           # 线程池相关
  53.           threadPool:
  54.             class: org.quartz.simpl.SimpleThreadPool
  55.             # 线程数
  56.             threadCount: 10
  57.             # 线程优先级
  58.             threadPriority: 5
  59.             threadsInheritContextClassLoaderOfInitializingThread: true
  60. mybatis-plus:
  61.   global-config:
  62.     db-config:
  63.       logic-delete-field: is_deleted
  64.       logic-delete-value: 1
  65.       logic-not-delete-value: 0
  66.   configuration:
  67.     log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  68. logging:
  69.   level:
  70.     com.my.quartz: debug
复制代码
添加sys_job表
  1. CREATE TABLE `sys_job` (
  2.   `id` bigint(11) NOT NULL AUTO_INCREMENT,
  3.   `job_id` varchar(100) DEFAULT NULL,
  4.   `job_name` varchar(255) DEFAULT NULL,
  5.   `job_group_name` varchar(255) DEFAULT NULL,
  6.   `invoke_target` varchar(255) NOT NULL,
  7.   `cron_expression` varchar(50) DEFAULT NULL,
  8.   `misfire_policy` varchar(255) DEFAULT NULL COMMENT 'cron计划策略0=默认,1=立即触发执行,2=触发一次执行,3=不触发立即执行',
  9.   `status` varchar(10) DEFAULT NULL COMMENT '任务状态(0正常 1暂停)',
  10.   `concurrent` varchar(10) DEFAULT NULL COMMENT '是否并发执行(0允许 1禁止)',
  11.   PRIMARY KEY (`id`)
  12. ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
复制代码
写两条数据

依次实现mvc三层



  • mapper层的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.my.quartz.boot.mapper.SysJobMapper">
  4.     <resultMap id="BaseResultMap" type="com.my.quartz.boot.SysJob">
  5.         <id column="id" jdbcType="BIGINT" property="id" />
  6.         <result column="job_id" jdbcType="VARCHAR" property="jobId" />
  7.         <result column="job_name" jdbcType="VARCHAR" property="jobName" />
  8.         <result column="job_group_name" jdbcType="VARCHAR" property="jobGroupName" />
  9.         <result column="invoke_target" jdbcType="VARCHAR" property="invokeTarget" />
  10.         <result column="cron_expression" jdbcType="VARCHAR" property="cronExpression" />
  11.         <result column="misfire_policy" jdbcType="VARCHAR" property="misfirePolicy" />
  12.         <result column="status" jdbcType="VARCHAR" property="status" />
  13.         <result column="concurrent" jdbcType="VARCHAR" property="concurrent" />
  14.     </resultMap>
  15.     <sql id="Base_Column_List">
  16.         t.id, t.job_id jobId, t.job_name jobName, t.job_group_name jobGroupName, t.invoke_target invokeTarget, t.cron_expression cronExpression, t.misfire_policy misfirePolicy, t.status, t.concurrent
  17.     </sql>
  18. </mapper>
复制代码


  • mapper接口
  1. /**
  2. * Auto Generated
  3. *
  4. * @author :Boy
  5. * @date :Created in 2022-06-18
  6. * @description:
  7. * @modified By:
  8. */
  9. public interface SysJobMapper extends BaseMapper<SysJob> {
  10. }
复制代码


  • service接口
  1. public interface SysJobService extends IService<SysJob> {
  2. }
复制代码


  • service接口实现
  1. @Service
  2. public class SysJobServiceImpl extends ServiceImpl<SysJobMapper, SysJob> implements SysJobService {
  3.     @Autowired
  4.     private Scheduler scheduler;
  5.     @Autowired
  6.     private ScheduleUtils scheduleUtils;
  7.     /**
  8.      * 项目启动时,初始化定时器
  9.      * 主要是防止手动修改数据库导致未同步到定时任务处理(注:不能手动修改数据库ID和任务组名,否则会导致脏数据)
  10.      */
  11.     @PostConstruct
  12.     public void init() throws SchedulerException, TaskException {
  13.         scheduler.clear();
  14.         List<SysJob> jobList = baseMapper.selectList(null);
  15.         for (SysJob job : jobList) {
  16.             scheduleUtils.createScheduleJob(scheduler, job);
  17.         }
  18.     }
  19. }
复制代码


  • controller代码
  1. @RestController
  2. @RequestMapping("/job")
  3. public class SysJobController {
  4.     @Resource
  5.     private SysJobService sysJobService;
  6.     @Resource
  7.     private ScheduleUtils scheduleUtils;
  8.     @Resource
  9.     private Scheduler scheduler;
  10.     @PostMapping("/add")
  11.     public Object add(@RequestBody SysJob entity) throws SchedulerException, TaskException {
  12.         sysJobService.save(entity);
  13.         scheduleUtils.createScheduleJob(scheduler, entity);
  14.         return "ok";
  15.     }
  16. }
复制代码


  • ScheduleUtils 定时任务工具类
  1. /**
  2. * @Author ScholarTang
  3. * @Date 2021/7/15 下午3:50
  4. * @Desc 定时任务工具类
  5. */
  6. @Component
  7. public class ScheduleUtils {
  8.     @Autowired
  9.     private Scheduler scheduler;
  10.     /**
  11.      * 构建任务触发对象
  12.      *
  13.      * @param jobName
  14.      * @param jobGroup
  15.      * @return
  16.      */
  17.     public TriggerKey getTriggerKey(String jobName, String jobGroup) {
  18.         return TriggerKey.triggerKey(jobName, jobGroup);
  19.     }
  20.     /**
  21.      * 构建任务键对象
  22.      *
  23.      * @param jobName
  24.      * @param jobGroup
  25.      * @return
  26.      */
  27.     public JobKey getJobKey(String jobName, String jobGroup) {
  28.         return JobKey.jobKey(jobName, jobGroup);
  29.     }
  30.     /**
  31.      * 创建定时调度任务
  32.      *
  33.      *
  34.      * @param scheduler
  35.      * @param job
  36.      * @throws SchedulerException
  37.      * @throws TaskException
  38.      */
  39.     public void createScheduleJob(Scheduler scheduler, SysJob job) throws SchedulerException, TaskException {
  40.         // 构建job信息
  41.         String jobName = job.getJobId() + "_" + job.getJobName();
  42.         String jobGroupName = job.getJobGroupName();
  43.         //TODO 反射动态获取Job实现类
  44.         //构建job实例
  45.         JobDetail jobDetail = JobBuilder.newJob(QuartzJobImpl.class)
  46.                 .withIdentity(getJobKey(jobName, jobGroupName))
  47.                 .build();
  48.         jobDetail.getJobDataMap().put("QuartzJobExecutionData", job);
  49.         // 表达式调度构建器
  50.         CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(job.getCronExpression());
  51.         cronScheduleBuilder = handleCronScheduleMisfirePolicy(job, cronScheduleBuilder);
  52.         // 按新的cronExpression表达式构建一个新的trigger
  53.         CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(getTriggerKey(jobName, jobGroupName))
  54.                 .withSchedule(cronScheduleBuilder).build();
  55.         // 放入参数,运行时的方法可以获取
  56.         jobDetail.getJobDataMap().put("QuartzJobExecutionData", job);
  57.         // 判断是否存在
  58.         if (scheduler.checkExists(getJobKey(jobName, jobGroupName))) {
  59.             // 防止创建时存在数据问题 先移除,然后在执行创建操作
  60.             scheduler.deleteJob(getJobKey(jobName, jobGroupName));
  61.         }
  62.         //创建定时任务调度
  63.         scheduler.scheduleJob(jobDetail, trigger);
  64.         // 暂停任务 规定 0启动 1暂停
  65.         if (job.getStatus().equals("1")) {
  66.             scheduler.pauseJob(getJobKey(jobName, jobGroupName));
  67.         }
  68.     }
  69.     /**
  70.      * 删除定时调度任务
  71.      *
  72.      * @param sysJob
  73.      * @throws SchedulerException
  74.      */
  75.     public void deleteScheduleJob(SysJob sysJob) throws SchedulerException {
  76.         scheduler.deleteJob(getJobKey(sysJob.getJobId() + "_" + sysJob.getJobName(), sysJob.getJobGroupName()));
  77.     }
  78.     /**
  79.      * 设置定时任务策略
  80.      *
  81.      * @param sysJob
  82.      * @param cronScheduleBuilder
  83.      * @return
  84.      */
  85.     public CronScheduleBuilder handleCronScheduleMisfirePolicy(SysJob sysJob, CronScheduleBuilder cronScheduleBuilder) throws TaskException {
  86.         switch (sysJob.getMisfirePolicy()) {
  87.             case "0":
  88.                 return cronScheduleBuilder;
  89.             case "1":
  90.                 return cronScheduleBuilder.withMisfireHandlingInstructionIgnoreMisfires();
  91.             case "2":
  92.                 return cronScheduleBuilder.withMisfireHandlingInstructionFireAndProceed();
  93.             case "3":
  94.                 return cronScheduleBuilder.withMisfireHandlingInstructionDoNothing();
  95.             default:
  96.                 throw new TaskException("任务失败策略 '" + sysJob.getMisfirePolicy()
  97.                         + "' 不能在cron计划任务中使用", TaskException.Code.CONFIG_ERROR);
  98.         }
  99.     }
  100. }
复制代码


  • 创建一个Job实现类,只是一个简单实现类,没有对方法添加参数
  1. @Slf4j
  2. @Component
  3. public class QuartzJobImpl implements Job {
  4.     @Autowired
  5.     private ApplicationContext context;
  6.     @SneakyThrows
  7.     @Override
  8.     public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
  9.         SysJob sysJob = new SysJob();
  10.         BeanUtils.copyProperties(jobExecutionContext.getMergedJobDataMap().get("QuartzJobExecutionData"), sysJob);
  11.         log.info("正在执行任务");
  12.         String invokeTarget = sysJob.getInvokeTarget();
  13.         String beanName = invokeTarget.split("\\.")[0];
  14.         String methodName = invokeTarget.split("\\.")[1];
  15.         Object bean = context.getBean(beanName);
  16.         Class<?> clazz = bean.getClass();
  17.         Method method = clazz.getMethod(methodName);
  18.         method.invoke(bean);
  19.         log.info("已结束任务");
  20.         System.out.println();
  21.     }
  22. }
复制代码


  • 创建最终任务执行类,执行函数级别的定时任务,数据库中的invoke_target是和这里放入spring中的名称相同的,quartz_target.hello最终执行的函数就是hello函数
  1. @Slf4j
  2. @Component("quartz_target")
  3. public class QuartzJobExe {
  4.     @Resource
  5.     private Scheduler scheduler;
  6.     public void hello() throws Exception {
  7.         System.out.println("[job]实例执行...hello..." + System.currentTimeMillis());
  8.     }
  9.     public void action() throws Exception {
  10.         System.out.println("[job]实例执行...action..." + System.currentTimeMillis());
  11.     }
  12. }
复制代码


  • 最终代码结构

  • 启动spring boot之后的任务状态

  • 使用postman工具类添加一个任务

  • 然后在代码中添加一个对应的方法

  • 重新启动springboot的运行结果

   理论上使用这样的反射方式可以运行任何代码的

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

九天猎人

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表