全局注册,所有Job都会起作用
JobCountListener listener = new JobCountListener();
sched.getListenerManager().addJobListener(listener);
给固定的job添加监听器
JobCountListener listener = new JobCountListener();
Matcher<JobKey> matcher = KeyMatcher.keyEquals(new JobKey("hello3", "group1"));
scheduler.getListenerManager().addJobListener(listener, matcher);
指定一组任务
GroupMatcher<JobKey> matcher = GroupMatcher.jobGroupEquals("group1");
sched.getListenerManager().addJobListener(new MyJobListener(), matcher);
可以根据组的名字匹配开头和结尾或包含
JobCountListener listener = new JobCountListener();
GroupMatcher<JobKey> matcher = GroupMatcher.groupStartsWith("g");
//GroupMatcher<JobKey> matcher = GroupMatcher.groupContains("g");
scheduler.getListenerManager().addJobListener(listener, matcher);
/**
* @author sky
*/
public class JobCountListener implements org.quartz.JobListener {
private Integer count;
public String getName() {
return "job监听";
}
public void jobToBeExecuted(JobExecutionContext jobExecutionContext) {
System.out.println("任务执行前。");
}
public void jobExecutionVetoed(JobExecutionContext jobExecutionContext) {
System.out.println("如果当TriggerListener中的vetoJobExecution方法返回true时,那么执行这个方法。任务被终止");
}
public void jobWasExecuted(JobExecutionContext jobExecutionContext, JobExecutionException e) {
JobDetail jobDetail = jobExecutionContext.getJobDetail();
System.out.println("Job :" + jobDetail.getKey().getGroup() + "." + jobDetail.getKey().getName());
Integer current = (Integer) jobExecutionContext.getJobDetail().getJobDataMap().get("count");
System.out.println("调用次数:" + current);
}
}
package com.sky.JobSchedule.Job;
import org.quartz.*;
import org.springframework.stereotype.Component;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* @author sky
*/
@Component
@DisallowConcurrentExecution
@PersistJobDataAfterExecution
public class JobCron implements Job {
String name;
public JobCron() {
System.out.println("Hello, Quartz sky! ----------------------");
}
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
JobDataMap jobDataMap = jobExecutionContext.getJobDetail().getJobDataMap();
Integer count = (Integer) jobDataMap.get("count");
if(count==null){
count=0;
}
count++;
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println("Hello, " + count + " sky !" + formatter.format(new Date()));
jobExecutionContext.getJobDetail().getJobDataMap().put("count", count);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
重启服务,需要重新添加监听器。