@Slf4j //创建一个Job
public class HelloTriggerListenerJob implements Job {
@Override
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
//输出时间
Date date = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat();
String dataTime = dateFormat.format(date);
log.info("当前系统时间为:"+dataTime);
}
}
//创建一个启动类
class HelloTriggerListenerDemo{
public static void main(String[] args) throws SchedulerException {
//1 获取调度器
Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
//2 获取任务实例Jobdetail
JobDetail jobDetail = JobBuilder.newJob(HelloTriggerListenerJob.class)
.withIdentity("Job1", "group1")
.build();
//3 生成触发器
Trigger trigger = TriggerBuilder.newTrigger()
.withIdentity("trigger1", "group1")
.startNow()
.withSchedule(SimpleScheduleBuilder
.repeatSecondlyForever(5)
.withRepeatCount(2))
.build();
//4 关联任务和触发器 保证按照触发器定义的条件执行任务
scheduler.scheduleJob(jobDetail,trigger);
//创建并注册一个全局的Trigger Llistener
//scheduler.getListenerManager().addTriggerListener(new HelloTriggerListener("simpleName"), EverythingMatcher.allTriggers());
//创建并注册一个局部的Trigger Llistener
scheduler.getListenerManager().addTriggerListener(new HelloTriggerListener("simpleListener"), KeyMatcher.keyEquals(TriggerKey.triggerKey("trigger1", "group1")));
//5 启动
scheduler.start();
}
}
//创建一个监听器监听trigger
@Slf4j
class HelloTriggerListener implements TriggerListener {
private String name;
public HelloTriggerListener(String name) {
this.name = name;
}
@Override //获取触发器的名称
public String getName() {
//打印并返回默认的NAME
// String simpleName = this.getClass().getSimpleName();
// log.info("触发器的名字为"+simpleName);
// return simpleName;
//打印并返回传来的name
log.info("触发器的名字为"+name);
return name;
}
/**
* 当与监听器相关联的trigger被触发,job上的excute()方法将被执行时,
* Scheduler被调用该方法
* @param trigger
* @param jobExecutionContext
*/
@Override
public void triggerFired(Trigger trigger, JobExecutionContext jobExecutionContext) {
String name = trigger.getKey().getName();
log.info(name+"被触发");
}
/**
* 当Trigger触发后,Job将要被执行时由Scheduler调用这个方法.TriggerListener给一个选择去否决Job的方法
* 假如这个方法返回true,这个job将不会为此次Trigger触发而得到执行
* @param trigger
* @param jobExecutionContext
* @return
*/
@Override //
public boolean vetoJobExecution(Trigger trigger, JobExecutionContext jobExecutionContext) {
String name = trigger.getKey().getName();
log.info("没有触发");
return false;
}
/**
* Scheduler调用这个方法是在Trigger错过触发时
* @param trigger
*/
@Override
public void triggerMisfired(Trigger trigger) {
String name = trigger.getKey().getName();
log.info("错过触发");
}
/**
* Trigger被触发并且完成了Job的执行时,Scheduler调用这个方法
*/
@Override
public void triggerComplete(Trigger trigger, JobExecutionContext jobExecutionContext, Trigger.CompletedExecutionInstruction completedExecutionInstruction) {
String name = trigger.getKey().getName();
log.info("完成触发");
}
}
网友评论