master
wxy 2024-05-24 13:55:48 +08:00
parent a86736da7d
commit a3e158cdb9
1 changed files with 106 additions and 0 deletions

View File

@ -0,0 +1,106 @@
package com.jing.job.util;
import java.util.Date;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.jing.common.core.constant.ScheduleConstants;
import com.jing.common.core.utils.ExceptionUtil;
import com.jing.common.core.utils.SpringUtils;
import com.jing.common.core.utils.StringUtils;
import com.jing.common.core.utils.bean.BeanUtils;
import com.jing.job.domain.SysJob;
import com.jing.job.domain.SysJobLog;
import com.jing.job.service.ISysJobLogService;
/**
* quartz
*
* @author ruoyi
*/
public abstract class AbstractQuartzJob implements Job
{
private static final Logger log = LoggerFactory.getLogger(AbstractQuartzJob.class);
/**
* 线
*/
private static ThreadLocal<Date> threadLocal = new ThreadLocal<>();
@Override
public void execute(JobExecutionContext context) throws JobExecutionException
{
SysJob sysJob = new SysJob();
BeanUtils.copyBeanProp(sysJob, context.getMergedJobDataMap().get(ScheduleConstants.TASK_PROPERTIES));
try
{
before(context, sysJob);
if (sysJob != null)
{
doExecute(context, sysJob);
}
after(context, sysJob, null);
}
catch (Exception e)
{
log.error("任务执行异常 - ", e);
after(context, sysJob, e);
}
}
/**
*
*
* @param context
* @param sysJob
*/
protected void before(JobExecutionContext context, SysJob sysJob)
{
threadLocal.set(new Date());
}
/**
*
*
* @param context
* @param sysJob
*/
protected void after(JobExecutionContext context, SysJob sysJob, Exception e)
{
Date startTime = threadLocal.get();
threadLocal.remove();
final SysJobLog sysJobLog = new SysJobLog();
sysJobLog.setJobName(sysJob.getJobName());
sysJobLog.setJobGroup(sysJob.getJobGroup());
sysJobLog.setInvokeTarget(sysJob.getInvokeTarget());
sysJobLog.setStartTime(startTime);
sysJobLog.setStopTime(new Date());
long runMs = sysJobLog.getStopTime().getTime() - sysJobLog.getStartTime().getTime();
sysJobLog.setJobMessage(sysJobLog.getJobName() + " 总共耗时:" + runMs + "毫秒");
if (e != null)
{
sysJobLog.setStatus("1");
String errorMsg = StringUtils.substring(ExceptionUtil.getExceptionMessage(e), 0, 2000);
sysJobLog.setExceptionInfo(errorMsg);
}
else
{
sysJobLog.setStatus("0");
}
// 写入数据库当中
SpringUtils.getBean(ISysJobLogService.class).addJobLog(sysJobLog);
}
/**
*
*
* @param context
* @param sysJob
* @throws Exception
*/
protected abstract void doExecute(JobExecutionContext context, SysJob sysJob) throws Exception;
}