上一章介绍监控job有三种方案,其实还有一个简单方案是实现quartz的TriggerListener。
上次我也试了这个方案,但是由于操作错误,导致没有监控成功,所以才选择分析源码来实现代理进行监控。
后面我看了些资料,并重新试了下,这种方案是可行的,并且非常方便。
首先实现TriggerListener,如下:
代码语言:javascript复制public class MonitorTriggerListener implements TriggerListener {
private final static Logger logger=Logger.getLogger(MonitorJobRunShell.class);
private ThreadLocal<QuartzLog> localLog=new ThreadLocal<QuartzLog>();
/**
* @see org.quartz.TriggerListener#getName()
*/
@Override
public String getName() {
return "MonitorTriggerListener";
}
/**
* @see org.quartz.TriggerListener#triggerComplete(org.quartz.Trigger, org.quartz.JobExecutionContext, int)
*/
@Override
public void triggerComplete(Trigger arg0, JobExecutionContext jec, int arg2) {
try {
QuartzLog quartzLog=localLog.get();
if(quartzLog==null)return ;
quartzLog.setExeTime(jec.getJobRunTime());
getService().update(quartzLog);
} catch (Exception e) {
logger.error("记录job结束时间异常",e);
}catch (Throwable e) {
logger.error("记录job结束时间出错",e);
}
}
/**
* @see org.quartz.TriggerListener#triggerFired(org.quartz.Trigger, org.quartz.JobExecutionContext)
*/
@Override
public void triggerFired(Trigger arg0, JobExecutionContext jec) {
try {
JobDetail jobDetail = jec.getJobDetail();
System.out.println(localLog.get());
QuartzLog quartzLog=getService().insert(jobDetail.getName());
localLog.set(quartzLog);
System.out.println(quartzLog);
} catch (Exception e) {
logger.error("记录job开始时间异常",e);
}catch (Throwable e) {
logger.error("记录job开始时间出错",e);
}
}
/**
* @see org.quartz.TriggerListener#triggerMisfired(org.quartz.Trigger)
*/
@Override
public void triggerMisfired(Trigger arg0) {
}
/**
* @see org.quartz.TriggerListener#vetoJobExecution(org.quartz.Trigger, org.quartz.JobExecutionContext)
*/
@Override
public boolean vetoJobExecution(Trigger arg0, JobExecutionContext arg1) {
return false;
}
private QuartzLogService getService(){
return (QuartzLogService)BeanLocator.getBeanInstance("quartzLogService");
}
}
然后在初始化StdSchedulerFactory时添加全局监听器,
代码语言:javascript复制factory = new StdSchedulerFactory(configProperties);
//启动调度
scheduler = factory.getScheduler();
TriggerListener myListener=new MonitorTriggerListener();
scheduler.addGlobalTriggerListener(myListener);
scheduler.start();
这样同样可以达到监控效果。