潘志宝
2024-08-20 92d87eda945d68346475e6766673a3cdccf3d41c
提交 | 用户 | 时间
a6de49 1 /**
H 2  * Copyright (c) 2018 人人开源 All rights reserved.
3  *
4  * https://www.renren.io
5  *
6  * 版权所有,侵权必究!
7  */
8
9 package com.iailab.module.job.utils;
10
11 import com.iailab.framework.common.constant.Constant;
12 import com.iailab.framework.common.exception.ExceptionUtils;
13 import com.iailab.framework.common.util.spring.SpringContextUtils;
14 import com.iailab.module.job.entity.ScheduleJobEntity;
15 import com.iailab.module.job.entity.ScheduleJobLogEntity;
16 import org.quartz.JobExecutionContext;
17 import org.slf4j.Logger;
18 import org.slf4j.LoggerFactory;
19 import org.springframework.scheduling.quartz.QuartzJobBean;
20
21 import java.lang.reflect.Method;
22 import java.util.Date;
23
24
25 /**
26  * 定时任务
27  *
28  * @author Mark sunlightcs@gmail.com
29  */
30 public class ScheduleJob extends QuartzJobBean {
31     private Logger logger = LoggerFactory.getLogger(getClass());
32
33     @Override
34     protected void executeInternal(JobExecutionContext context) {
35         ScheduleJobEntity scheduleJob = (ScheduleJobEntity) context.getMergedJobDataMap().
36                 get(ScheduleUtils.JOB_PARAM_KEY);
37
38         //数据库保存执行记录
39         ScheduleJobLogEntity log = new ScheduleJobLogEntity();
40         log.setJobId(scheduleJob.getId());
41         log.setBeanName(scheduleJob.getBeanName());
42         log.setParams(scheduleJob.getParams());
43         log.setCreateDate(new Date());
44
45         //任务开始时间
46         long startTime = System.currentTimeMillis();
47
48         try {
49             //执行任务
50             logger.info("任务准备执行,任务ID:{}", scheduleJob.getId());
51             Object target = SpringContextUtils.getBean(scheduleJob.getBeanName());
52             Method method = target.getClass().getDeclaredMethod("run", String.class);
53             method.invoke(target, scheduleJob.getParams());
54
55             //任务执行总时长
56             long times = System.currentTimeMillis() - startTime;
57             log.setTimes((int)times);
58             //任务状态
59             log.setStatus(Constant.SUCCESS);
60
61             logger.info("任务执行完毕,任务ID:{}  总共耗时:{} 毫秒", scheduleJob.getId(), times);
62         } catch (Exception e) {
63             logger.error("任务执行失败,任务ID:{}", scheduleJob.getId(), e);
64
65             //任务执行总时长
66             long times = System.currentTimeMillis() - startTime;
67             log.setTimes((int)times);
68
69             //任务状态
70             log.setStatus(Constant.FAIL);
71             log.setError(ExceptionUtils.getErrorStackTrace(e));
72         }finally {
73             //获取spring bean
74             /*ScheduleJobLogService scheduleJobLogService = SpringContextUtils.getBean(ScheduleJobLogService.class);
75             scheduleJobLogService.insert(log);*/
76         }
77     }
78 }