Quartz Scheduler 可以對Job(任務)建立一個監聽器,分別對任務執行 《之前, 之后, 取消》 3個階段進行監聽。
實現監聽器需要實現JobListener接口,然后注冊到Scheduler上就可以了。
一:首先寫一個監聽器實現類
1 package com.gary.operation.jobdemo.example1; 2
3 import org.quartz.JobExecutionContext; 4 import org.quartz.JobExecutionException; 5 import org.quartz.JobListener; 6
7 public class MyJobListener implements JobListener { 8
9 @Override 10 public String getName() { 11 return "MyJobListener"; 12 } 13
14 /**
15 * (1) 16 * 任務執行之前執行 17 * Called by the Scheduler when a JobDetail is about to be executed (an associated Trigger has occurred). 18 */
19 @Override 20 public void jobToBeExecuted(JobExecutionContext context) { 21 System.out.println("MyJobListener.jobToBeExecuted()"); 22 } 23
24 /**
25 * (2) 26 * 這個方法正常情況下不執行,但是如果當TriggerListener中的vetoJobExecution方法返回true時,那么執行這個方法. 27 * 需要注意的是 如果方法(2)執行 那么(1),(3)這個倆個方法不會執行,因為任務被終止了嘛. 28 * Called by the Scheduler when a JobDetail was about to be executed (an associated Trigger has occurred), 29 * but a TriggerListener vetoed it's execution. 30 */
31 @Override 32 public void jobExecutionVetoed(JobExecutionContext context) { 33 System.out.println("MyJobListener.jobExecutionVetoed()"); 34 } 35
36 /**
37 * (3) 38 * 任務執行完成后執行,jobException如果它不為空則說明任務在執行過程中出現了異常 39 * Called by the Scheduler after a JobDetail has been executed, and be for the associated Trigger's triggered(xx) method has been called. 40 */
41 @Override 42 public void jobWasExecuted(JobExecutionContext context, 43 JobExecutionException jobException) { 44 System.out.println("MyJobListener.jobWasExecuted()"); 45 } 46
47 }
二:將這個監聽器注冊到Scheduler
假設有一個任務的key是 job1與 group1
// define the job and tie it to our HelloJob class
JobDetail job = newJob(HelloJob.class)
.withIdentity("job1", "group1")
.build();
全局注冊,所有Job都會起作用
Registering A JobListener With The Scheduler To Listen To All Jobs
sched.getListenerManager().addJobListener(new MyJobListener());
指定具體的任務
Registering A JobListener With The Scheduler To Listen To A Specific Job
Matcher<JobKey> matcher = KeyMatcher.keyEquals(new JobKey("job1", "group1"));
sched.getListenerManager().addJobListener(new MyJobListener(), matcher);
指定一組任務 Registering A JobListener With The Scheduler To Listen To All Jobs In a Group GroupMatcher<JobKey> matcher = GroupMatcher.jobGroupEquals("group1"); sched.getListenerManager().addJobListener(new MyJobListener(), matcher);
可以根據組的名字匹配開頭和結尾或包含
GroupMatcher<JobKey> matcher = GroupMatcher.groupStartsWith("g");
GroupMatcher<JobKey> matcher = GroupMatcher.groupContains("g");
sched.getListenerManager().addJobListener(new MyJobListener(), matcher);