Quartz使用监听器插入定时任务执行日志

打印 上一主题 下一主题

主题 528|帖子 528|积分 1584

Quartz使用监听器插入定时任务执行日志

使用springboot,将监听器交给spring容器管理,并像其中注入日志服务类,环境准备工作实现任务调度需要导入两个quartz的maven依赖
  1. <dependency>
  2.             <groupId>org.quartz-scheduler</groupId>
  3.             <artifactId>quartz</artifactId>
  4.             <version>2.3.2</version>
  5. </dependency>
  6. <dependency>
  7.             <groupId>org.springframework.boot</groupId>
  8.             <artifactId>spring-boot-starter-quartz</artifactId>
  9.             <version>2.7.3</version>
  10.             <exclusions>
  11.                 <exclusion>
  12.                     <artifactId>slf4j-api</artifactId>
  13.                     <groupId>org.slf4j</groupId>
  14.                 </exclusion>
  15.             </exclusions>
  16.   </dependency>      
  17.         
复制代码
创建一个监听器类,实现JobListener接口。
  1. import cn.hutool.core.date.DateUtil;
  2. import lombok.extern.slf4j.Slf4j;
  3. import org.quartz.JobDataMap;
  4. import org.quartz.JobExecutionContext;
  5. import org.quartz.JobExecutionException;
  6. import org.quartz.JobKey;
  7. import org.quartz.JobListener;
  8. import org.quartz.TriggerKey;
  9. import org.springframework.stereotype.Component;
  10. import java.util.Date;
  11. @Slf4j
  12. @Component
  13. public class QuartzJobListener implements JobListener {
  14.         private final QuartzRunningLogService logService;
  15.         private static ThreadLocal<QuartzRunningLog> logThreadLocal = ThreadLocal.withInitial(QuartzRunningLog::new);
  16.         public QuartzJobListener(QuartzRunningLogService logService) {
  17.                 this.logService = logService;
  18.         }
  19.         @Override
  20.         public String getName() {
  21.                 return "jobLogListener";
  22.         }
  23.         /**
  24.         *
  25.         *Scheduler在JobDetail将要被执行时调用这个方法
  26.         **/
  27.         @Override
  28.         public void jobToBeExecuted(JobExecutionContext context) {
  29.                 QuartzRunningLog quartzRunningLog = QuartzRunningLog
  30.                                 .builder()
  31.                                 .startTime(new Date())
  32.                                 .build();
  33.                 logThreadLocal.set(quartzRunningLog);
  34.         }
  35.         /**
  36.         *
  37.         *Scheduler在JobDetail即将被执行,但又被TriggerListerner否决时会调用该方法
  38.         **/
  39.         @Override
  40.         public void jobExecutionVetoed(JobExecutionContext jobExecutionContext) {
  41.         }
  42.         /**
  43.         *
  44.         *Scheduler在JobDetail被执行之后调用这个方法
  45.         **/
  46.         @Override
  47.         public void jobWasExecuted(JobExecutionContext context, JobExecutionException jobException) {
  48.                 JobKey jobKey = context.getJobDetail().getKey();
  49.                 TriggerKey triggerKey = context.getTrigger().getKey();
  50.                 Date fireTime = context.getFireTime();
  51.                 Class jobClass = context.getJobDetail().getJobClass();
  52.                 JobDataMap dataMap = context.getMergedJobDataMap();
  53.                 String taskName = (String) dataMap.get(CommonConst.TASK_NAME);
  54.                 String cronExpression = (String) dataMap.get(CommonConst.CRON_EXPRESSION);
  55.                 String jobName = (String) dataMap.get(CommonConst.JOB_NAME);
  56.                 log.info("JobClass:{},Job:{},Trigger:{},FireTime:{}", jobClass, jobKey, triggerKey, DateUtil.formatDateTime(fireTime));
  57.                 if (null != jobException) {
  58.                         //保存错误记录
  59.                         QuartzRunningLog runningLog = logThreadLocal.get();
  60.                         runningLog.setJobName(jobName);
  61.                         runningLog.setCronExpression(cronExpression);
  62.                         runningLog.setEndTime(new Date());
  63.                         runningLog.setStatus("FAIL");
  64.                         runningLog.setTaskId(Long.valueOf(jobKey.getName()));
  65.                         runningLog.setTaskName(taskName);
  66.                         runningLog.setFailReason(jobException.getMessage());
  67.                         logService.save(runningLog);
  68.                         logThreadLocal.remove();
  69.                         return;
  70.                 }
  71.                 //保存执行记录
  72.                 QuartzRunningLog runningLog = logThreadLocal.get();
  73.                 runningLog.setJobName(jobName);
  74.                 runningLog.setCronExpression(cronExpression);
  75.                 runningLog.setEndTime(new Date());
  76.                 runningLog.setStatus("SUCESS");
  77.                 runningLog.setTaskId(Long.valueOf(jobKey.getName()));
  78.                 runningLog.setTaskName(taskName);
  79.                 logService.save(runningLog);
  80.                 logThreadLocal.remove();
  81.         }
  82. }
复制代码
quartzconfig配置类
  1. import org.quartz.Scheduler;
  2. import org.quartz.SchedulerException;
  3. import org.quartz.spi.JobFactory;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.context.ApplicationContext;
  6. import org.springframework.context.annotation.Bean;
  7. import org.springframework.context.annotation.Configuration;
  8. import org.springframework.scheduling.quartz.SchedulerFactoryBean;
  9. @Configuration
  10. public class QuartzConfig {
  11.         @Autowired
  12.         private ApplicationContext applicationContext;
  13.         /**
  14.          * Create the job factory bean
  15.          *
  16.          * @return Job factory bean
  17.          */
  18.         @Bean
  19.         public JobFactory jobFactory() {
  20.                 ApplicationContextHolder jobFactory = new ApplicationContextHolder();
  21.                 jobFactory.setApplicationContext(applicationContext);
  22.                 return jobFactory;
  23.         }
  24.         /**
  25.          * Create the Scheduler Factory bean
  26.          *
  27.          * @return scheduler factory object
  28.          */
  29.         @Bean
  30.         public SchedulerFactoryBean schedulerFactory() {
  31.                 SchedulerFactoryBean factory = new SchedulerFactoryBean();
  32.                 factory.setAutoStartup(true);
  33.                 factory.setSchedulerName("Scheduler");
  34.                 factory.setOverwriteExistingJobs(true);
  35.                 factory.setJobFactory(jobFactory());
  36.                 return factory;
  37.         }
  38.         /**
  39.          * Create the Scheduler bean
  40.          *
  41.          * @param logService
  42.          * @return Scheduler
  43.          * @throws SchedulerException
  44.          */
  45.         @Bean
  46.         public Scheduler scheduler(@Autowired QuartzRunningLogService logService) throws SchedulerException {
  47.         //在这里注入日志服务类且激活监听器,如果直接在监听器类里面使用@Autowired会出现注入为null
  48.                 schedulerFactory().getScheduler().getListenerManager().addJobListener(new QuartzJobListener(logService));
  49.                 return schedulerFactory().getScheduler();
  50.         }
  51. }
复制代码
容器工具类
  1. import org.quartz.spi.TriggerFiredBundle;
  2. import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
  3. import org.springframework.context.ApplicationContext;
  4. import org.springframework.context.ApplicationContextAware;
  5. import org.springframework.scheduling.quartz.SpringBeanJobFactory;
  6. import org.springframework.stereotype.Component;
  7. @Component
  8. public class ApplicationContextHolder extends SpringBeanJobFactory
  9.                 implements ApplicationContextAware {
  10.         private static ApplicationContext context;
  11.         private transient AutowireCapableBeanFactory beanFactory;
  12.         @Override
  13.         public void setApplicationContext(final ApplicationContext context) {
  14.                 beanFactory = context.getAutowireCapableBeanFactory();
  15.                 ApplicationContextHolder.context = context;
  16.         }
  17.         @Override
  18.         protected Object createJobInstance(final TriggerFiredBundle bundle) throws Exception {
  19.                 final Object job = super.createJobInstance(bundle);
  20.                 beanFactory.autowireBean(job);
  21.                 return job;
  22.         }
  23.         public static ApplicationContext getContext() {
  24.                 return context;
  25.         }
  26. }
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

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

本版积分规则

河曲智叟

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

标签云

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