通过注入方式能取得service
@Inject
@Reference
protected QuartzJobService quartzJobService;
通过Ioc无法取得
QuartzJobService quartzJobService = ioc.get(QuartzJobService.class, "quartzJobService");
但是有些功能会存在随机性,全部都放静态变量的话会很乱,我提了个issue建议支持下,谢谢
是这样的,我封装了一个BaseJob
/**
* Created with IntelliJ IDEA.
*
* @author 306955302@qq.com
* @PersistJobDataAfterExecution 保存在JobDataMap传递的参数
* @DisallowConcurrentExecution 保证多个任务间不会同时执行.所以在多任务执行时最好加上
*/
@PersistJobDataAfterExecution
public abstract class BaseJob implements Job {
/**
* 任务缓存
*/
public static final String KEY_JOB_ENTITY = "KEY_JOB_ENTITY";
/**
* 任务运行参数
* 修改后需要先停止再启动,才能生效
*/
public static final String KEY_JOB_RUN_ARGS = "KEY_JOB_RUN_ARGS";
protected static final Log log = Logs.get();
protected Ioc ioc;
/**
* TODO 此为临时解决方案
*/
public static JobRunHistoryService jobRunHistoryService;
/**
* TODO 此为临时解决方案
*/
public static QuartzJobService quartzJobService;
public BaseJob(Ioc ioc) {
this.ioc = ioc;
// this.quartzJobService = ioc.get(QuartzJobService.class, "quartzJobService");
// this.jobRunHistoryService = ioc.get(JobRunHistoryService.class, "jobRunHistoryService");
}
@Override
final public void execute(JobExecutionContext context) {
JobDataMap data = context.getJobDetail().getJobDataMap();
QuartzJob quartzJob = (QuartzJob) data.get(KEY_JOB_ENTITY);
if (null != quartzJob) {
//上次状态
boolean lastStatus = quartzJob.isJobLastStatus();
long startTime = System.currentTimeMillis();
try {
quartzJob.setJobStatus("RUNING");
run(data);
quartzJob.setJobStatus("NORMAL");
quartzJob.setJobLastStatus(true);
//考虑了下不记录成功日志
} catch (Exception e) {
log.error(e);
JobRunHistory history = new JobRunHistory();
history.setJobId(quartzJob.getUuid());
quartzJob.setJobStatus("NORMAL");
quartzJob.setJobLastStatus(false);
history.setStatus(false);
history.setErrorLog(Strings.escapeHtml(StringUtil.throwableToString(e)));
long endTime = System.currentTimeMillis();
history.setConsuming(DateUtil.getDistanceTime(startTime, endTime, "{H}小时{M}分{S}秒{MS}毫秒"));
jobRunHistoryService.insert(history);
} finally {
long endTime = System.currentTimeMillis();
quartzJob.setLastConsuming(DateUtil.getDistanceTime(startTime, endTime, "{H}小时{M}分{S}秒{MS}毫秒"));
if (lastStatus != quartzJob.isJobLastStatus()) {
//当前状态和上次状态不一样
quartzJobService.update(quartzJob);
}
}
} else {
try {
//没有将任务对象加载进任务缓存
run(data);
} catch (Exception e) {
log.error(e);
}
}
}
/**
* 任务运行逻辑处理
*
* @param data
* @throws Exception
*/
public abstract void run(JobDataMap data) throws Exception;
}
@wendal @Wizzercn