沙钢智慧能源系统后端代码
liriming
2024-12-02 8766cfc344d3635cd7e50a7c674cd5feb54d5a3d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package com.iailab.module.shasteel.job.utils;
 
import com.iailab.framework.common.constant.Constant;
import com.iailab.framework.common.exception.ExceptionUtils;
import com.iailab.module.shasteel.job.entity.ScheduleJobEntity;
import com.iailab.module.shasteel.job.entity.ScheduleJobLogEntity;
import com.iailab.module.shasteel.util.SpringContextUtils;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.JobExecutionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.quartz.QuartzJobBean;
 
import java.lang.reflect.Method;
import java.util.Date;
 
 
/**
 * 定时任务
 *
 * @author Mark sunlightcs@gmail.com
 */
@DisallowConcurrentExecution
public class ScheduleJob extends QuartzJobBean {
    private Logger logger = LoggerFactory.getLogger(getClass());
 
    @Override
    protected void executeInternal(JobExecutionContext context) {
        ScheduleJobEntity scheduleJob = (ScheduleJobEntity) context.getMergedJobDataMap().
                get(ScheduleUtils.JOB_PARAM_KEY);
 
        //数据库保存执行记录
        ScheduleJobLogEntity log = new ScheduleJobLogEntity();
        log.setJobId(scheduleJob.getId());
        log.setBeanName(scheduleJob.getBeanName());
        log.setParams(scheduleJob.getParams());
        log.setCreateDate(new Date());
 
        //任务开始时间
        long startTime = System.currentTimeMillis();
        
        try {
            //执行任务
            logger.info("任务准备执行,任务ID:{}", scheduleJob.getId());
            Object target = SpringContextUtils.getBean(scheduleJob.getBeanName());
            Method method = target.getClass().getDeclaredMethod("run", String.class);
            method.invoke(target, scheduleJob.getParams());
 
            //任务执行总时长
            long times = System.currentTimeMillis() - startTime;
            log.setTimes((int)times);
            //任务状态
            log.setStatus(Constant.SUCCESS);
            
            logger.info("任务执行完毕,任务ID:{}  总共耗时:{} 毫秒", scheduleJob.getId(), times);
        } catch (Exception e) {
            logger.error("任务执行失败,任务ID:{}", scheduleJob.getId(), e);
            
            //任务执行总时长
            long times = System.currentTimeMillis() - startTime;
            log.setTimes((int)times);
            
            //任务状态
            log.setStatus(Constant.FAIL);
            log.setError(ExceptionUtils.getErrorStackTrace(e));
        }finally {
            //获取spring bean
            /*ScheduleJobLogService scheduleJobLogService = SpringContextUtils.getBean(ScheduleJobLogService.class);
            scheduleJobLogService.insert(log);*/
        }
    }
}