概述
与 JobListener 有所不同的是, TriggerListener 接口还有关于 Trigger 实例生命周期的方法。
TriggerListener接口方法
我们先看下TriggerListener的源码
import org.quartz.Trigger.CompletedExecutionInstruction; public interface TriggerListener { String getName(); void triggerFired(Trigger var1, JobExecutionContext var2); boolean vetoJobExecution(Trigger var1, JobExecutionContext var2); void triggerMisfired(Trigger var1); void triggerComplete(Trigger var1, JobExecutionContext var2, CompletedExecutionInstruction var3); }
getName():和前面的 JobListener 一样,TriggerListner 接口的 getName()返回一个字符串用以说明监听器的名称。对于非全局的 TriggerListener,在 addTriggerListener()方法中给定的名称必须与监听器的 getName() 方法返回值相匹配。
triggerFired() :当与监听器相关联的 Trigger 被触发,Job 上的 execute()方法将要被执行时,Scheduler 就调用这个方法。在全局 TriggerListener 情况下,这个方法为所有 Trigger被调用。
vetoJobExecution():在 Trigger 触发后,Job 将要被执行时由 Scheduler调用这个方法。TriggerListener 给了一个选择去否决 Job 的执行。假如这个方法返回 true,这个 Job 将不会为此次Trigger 触发而得到执行。
triggerMisfired():Scheduler 调用这个方法是在 Trigger 错过触发时。如这个方法的 JavaDoc所指出的,你应该关注此方法中持续时间长的逻辑:在出现许多错过触发的 Trigger 时,长逻辑会导致骨牌效应。你应当保持这上方法尽量的小。
triggerComplete():Trigger 被触发并且完成了 Job 的执行时,Scheduler 调用这个方法。这不是说这个Trigger 将不再触发了,而仅仅是当前 Trigger 的触发(并且紧接着的 Job 执行) 结束时。这个 Trigger也许还要在将来触发多次的。
示例
Job
package com.xgj.quartz.quartzItself.listener.triggerListener; import java.text.SimpleDateFormat; import java.util.Date; import org.quartz.Job; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; import org.quartz.JobKey; public class SimpleJob1 implements Job { public void execute(JobExecutionContext context) throws JobExecutionException { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); JobKey jobKey = context.getJobDetail().getKey(); System.out.println("\nJob1 - 任务key " + jobKey + "执行时间:" + sdf.format(new Date())); } }
Job
package com.xgj.quartz.quartzItself.listener.triggerListener; import java.text.SimpleDateFormat; import java.util.Date; import org.quartz.Job; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; import org.quartz.JobKey; public class SimpleJob2 implements Job { public void execute(JobExecutionContext context) throws JobExecutionException { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); JobKey jobKey = context.getJobDetail().getKey(); System.err.println("\nJob2 - 任务key " + jobKey + "执行时间:" + sdf.format(new Date())); } }
自定义TriggerListener
package com.xgj.quartz.quartzItself.listener.triggerListener; import org.quartz.JobExecutionContext; import org.quartz.Trigger; import org.quartz.TriggerListener; public class MyTriggerListener implements TriggerListener { @Override public String getName() { return "MyTriggerListener"; } /** * (1) Trigger被激发 它关联的job即将被运行 * * @param trigger * @param context */ @Override public void triggerFired(Trigger trigger, JobExecutionContext context) { System.out.println("MyTrigger监听器:" + trigger.getJobKey() + ",进入方法 triggerFired()"); } /** * (2) Trigger被激发 它关联的job即将被运行,先执行(1),在执行(2) 如果返回TRUE 那么任务job会被终止 * * @param trigger * @param context * @return */ @Override public boolean vetoJobExecution(Trigger trigger, JobExecutionContext context) { System.out.println("MyTrigger监听器:" + trigger.getJobKey() + ",vetoJobExecution()"); return false; } /** * (3) 当Trigger错过被激发时执行,比如当前时间有很多触发器都需要执行,但是线程池中的有效线程都在工作,那么有的触发器就有可能超时, * 错过这一轮的触发。 * * @param trigger */ @Override public void triggerMisfired(Trigger trigger) { System.out.println("MyTrigger监听器:" + trigger.getJobKey() + ",triggerMisfired()"); } /** * (4) 任务完成时触发 * * @param trigger * @param jobExecutionContext * @param completedExecutionInstruction */ @Override public void triggerComplete(Trigger trigger, JobExecutionContext jobExecutionContext, Trigger.CompletedExecutionInstruction completedExecutionInstruction) { System.out.println("MyTrigger监听器:" + trigger.getJobKey() + ",triggerComplete()"); } }
调度类
package com.xgj.quartz.quartzItself.listener.triggerListener; import static org.quartz.JobBuilder.newJob; import static org.quartz.TriggerBuilder.newTrigger; import org.quartz.JobDetail; import org.quartz.Matcher; import org.quartz.Scheduler; import org.quartz.SchedulerFactory; import org.quartz.SchedulerMetaData; import org.quartz.Trigger; import org.quartz.TriggerKey; import org.quartz.TriggerListener; import org.quartz.impl.StdSchedulerFactory; import org.quartz.impl.matchers.KeyMatcher; public class TriggerListenerDemo { public static void main(String[] args) throws Exception { System.out.println("------- 初始化 ----------------------"); // Scheduler SchedulerFactory schedulerFactory = new StdSchedulerFactory(); Scheduler scheduler = schedulerFactory.getScheduler(); // Job JobDetail job = newJob(SimpleJob1.class).withIdentity("job1", "group1") .build(); // Tirgger Trigger trigger = newTrigger().withIdentity("trigger1", "group1") .startNow().build(); // 设置监听器 TriggerListener triggerListener = new MyTriggerListener(); Matcher<TriggerKey> matcher = KeyMatcher.keyEquals(trigger.getKey()); scheduler.getListenerManager().addTriggerListener(triggerListener, matcher); // 将job任务加入到调度器 scheduler.scheduleJob(job, trigger); // 开始任务 System.out.println("------- 开始执行调度器 Scheduler ----------------"); scheduler.start(); try { System.out.println("------- 等待 30 秒... --------------"); Thread.sleep(30L * 1000L); } catch (Exception e) { e.printStackTrace(); } scheduler.shutdown(true); System.out.println("------- 关闭调度器 -----------------"); SchedulerMetaData metaData = scheduler.getMetaData(); System.out.println("~~~~~~~~~~ 执行了 " + metaData.getNumberOfJobsExecuted() + " 个 jobs."); } }
运行结果
------- 初始化 ---------------------- INFO StdSchedulerFactory - Using default implementation for ThreadExecutor INFO SimpleThreadPool - Job execution threads will use class loader of thread: main INFO SchedulerSignalerImpl - Initialized Scheduler Signaller of type: class org.quartz.core.SchedulerSignalerImpl INFO QuartzScheduler - Quartz Scheduler v.2.2.3 created. INFO RAMJobStore - RAMJobStore initialized. INFO QuartzScheduler - Scheduler meta-data: Quartz Scheduler (v2.2.3) 'DefaultQuartzScheduler' with instanceId 'NON_CLUSTERED' Scheduler class: 'org.quartz.core.QuartzScheduler' - running locally. NOT STARTED. Currently in standby mode. Number of jobs executed: 0 Using thread pool 'org.quartz.simpl.SimpleThreadPool' - with 10 threads. Using job-store 'org.quartz.simpl.RAMJobStore' - which does not support persistence. and is not clustered. INFO StdSchedulerFactory - Quartz scheduler 'DefaultQuartzScheduler' initialized from default resource file in Quartz package: 'quartz.properties' INFO StdSchedulerFactory - Quartz scheduler version: 2.2.3 ------- 开始执行调度器 Scheduler ---------------- INFO QuartzScheduler - Scheduler DefaultQuartzScheduler_$_NON_CLUSTERED started. ------- 等待 30 秒... -------------- MyTrigger监听器:group1.job1,进入方法 triggerFired() MyTrigger监听器:group1.job1,vetoJobExecution() Job1 - 任务key group1.job1执行时间:2017-11-16 21:52:50 MyTrigger监听器:group1.job1,triggerComplete() INFO QuartzScheduler - Scheduler DefaultQuartzScheduler_$_NON_CLUSTERED shutting down. INFO QuartzScheduler - Scheduler DefaultQuartzScheduler_$_NON_CLUSTERED paused. INFO QuartzScheduler - Scheduler DefaultQuartzScheduler_$_NON_CLUSTERED shutdown complete. ------- 关闭调度器 ----------------- ~~~~~~~~~~ 执行了 1 个 jobs.
示例源码
代码已托管到Github—> https://github.com/yangshangwei/SpringMaster