quartz監控日誌(二)添加監聽器

 

上一章介紹監控job有三種方案,其實還有一個簡單方案是實現quartz的TriggerListener。java

上次我也試了這個方案,可是因爲操做錯誤,致使沒有監控成功,因此才選擇分析源碼來實現代理進行監控。ide

後面我看了些資料,並從新試了下,這種方案是可行的,而且很是方便。spa

首先實現TriggerListener,以下:代理

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時添加全局監聽器,code

factory = new StdSchedulerFactory(configProperties);
   //啓動調度
  scheduler = factory.getScheduler();
   TriggerListener myListener=new MonitorTriggerListener();
  scheduler.addGlobalTriggerListener(myListener);
  scheduler.start();

 這樣一樣能夠達到監控效果。blog

相關文章
相關標籤/搜索