Quartz入门 (四) 监听器Listener

  Quartz的监听器用于当任务调度中你所关注事件发生时,能够及时获取这一事件的通知。类似于任务执行过程中的邮件、短信类的提醒。Quartz 的监听器有Job监听器,Trigger监听器, Scheduler监听器,对不同层面进行监控。三者的使用方法类似,在开始介绍三种监听器之前,需要明确两个概念:全局监听器非全局监听器,二者的区别在于:全局监听器能够接收到所有的Job/Trigger的事件通知,而非全局监听器只能接收到在其上注册的Job或Trigger的事件,不在其上注册的Job或Trigger则不会进行监听。

 

JobListener

  任务调度过程中,与任务Job相关的事件包括:job开始要执行的提示; job执行完成的提示灯。

public interface JobListener {
    
  String getName();
void jobToBeExecuted(JobExecutionContext var1); void jobExecutionVetoed(JobExecutionContext var1); void jobWasExecuted(JobExecutionContext var1, JobExecutionException var2); }

Quartz入门 (四) 监听器Listener_第1张图片

 

 

demo:

自己写一个监听器实现JobListener接口:

public class MailJobListener implements JobListener {

    @Override
    public String getName() {
        return "listener of mail job";
    }

    @Override
    public void jobExecutionVetoed(JobExecutionContext context) {
        System.out.println("取消执行:\t "+context.getJobDetail().getKey());
    }

    @Override
    public void jobToBeExecuted(JobExecutionContext context) {
        System.out.println("准备执行:\t "+context.getJobDetail().getKey());
    }

    @Override
    public void jobWasExecuted(JobExecutionContext context, JobExecutionException arg1) {
        System.out.println("执行结束:\t "+context.getJobDetail().getKey());
        System.out.println();
    }

}

Job:

public class MailJob implements Job {

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        JobDetail detail=jobExecutionContext.getJobDetail();
        String email = detail.getJobDataMap().getString("email");

        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        String now = sdf.format(new Date());

        System.out.printf("给邮件地址 %s 发出了一封定时邮件, 当前时间是: %s%n" ,email, now);
    }
}


测试:

public class Test {
    public static void main(String[] args) throws Exception{

        Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();

        Trigger trigger= newTrigger()
                .withIdentity("trigger1","group1")
                .startNow()
                .withSchedule(simpleSchedule().withIntervalInSeconds(1).withRepeatCount(5))
                .build();

        JobDetail jobDetail=newJob(MailJob.class)
                .withIdentity("job1","group1")
                .usingJobData("email","臭弟弟")
                .build();

//这是自己写的那个监听器: MailJobListener mailJobListener
=new MailJobListener();
//构造匹配pickNewsJob中的JobKey的keyMatcher KeyMatcher keyMatcher = KeyMatcher.keyEquals(jobDetail.getKey());
//加入调度器: scheduler.getListenerManager().addJobListener(mailJobListener,keyMatcher); scheduler.scheduleJob(jobDetail,trigger); scheduler.start(); Thread.sleep(
20000); scheduler.shutdown(); } }

 

Quartz入门 (四) 监听器Listener_第2张图片

 

你可能感兴趣的:(Quartz入门 (四) 监听器Listener)