Quartz入门 监听器Listener
Posted crazy-lc
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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); }
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("取消执行: "+context.getJobDetail().getKey()); } @Override public void jobToBeExecuted(JobExecutionContext context) { System.out.println("准备执行: "+context.getJobDetail().getKey()); } @Override public void jobWasExecuted(JobExecutionContext context, JobExecutionException arg1) { System.out.println("执行结束: "+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<JobKey> keyMatcher = KeyMatcher.keyEquals(jobDetail.getKey());
//加入调度器: scheduler.getListenerManager().addJobListener(mailJobListener,keyMatcher); scheduler.scheduleJob(jobDetail,trigger); scheduler.start(); Thread.sleep(20000); scheduler.shutdown(); } }
以上是关于Quartz入门 监听器Listener的主要内容,如果未能解决你的问题,请参考以下文章
转:web.xml 中的listener filterservlet 加载顺序及其详解