quartz 的监听器 -->监听job(JobListener

2020-04-29  本文已影响0人  刘小刀tina

@Slf4j
public class HelloJobListerner  implements Job {
    private SimpleDateFormat format;

    @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 HelloJobListernerDemo{

    public static void main(String[] args) throws SchedulerException {
        //1 获取调度器
        Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
        //2 获取任务实例jobdetail
        JobDetail jobDetail = JobBuilder.newJob(HelloJobListerner.class)
                .withIdentity("job1", "group1")
                .build();
        //3 生成触发器
        SimpleTrigger trigger = TriggerBuilder.newTrigger()
                .withIdentity("trigger1", "group1")
                .startNow()
                .withSchedule(SimpleScheduleBuilder.
                        repeatSecondlyForever(5).//每5秒执行一次
                        withRepeatCount(0)) //循环执行3次
                .build();
        //4.关联任务和触发器 保证按照触发器定义的条件执行任务
        scheduler.scheduleJob(jobDetail,trigger);
        //创建并注册一个全局的Job Listerner
        //scheduler.getListenerManager().addJobListener(new MyJobListerner(), EverythingMatcher.allJobs());
        //创建并注册一个局部的Job Listerner
        scheduler.getListenerManager().addJobListener(new MyJobListerner(), KeyMatcher.keyEquals(JobKey.jobKey("job1", "group1")));

        //5.启动
         scheduler.start();

    }
}

//创建一个监听器
@Slf4j
class  MyJobListerner implements JobListener {

    //获取监听器的名称
    @Override
    public String getName() {
        String name = this.getClass().getSimpleName();
        log.info("监听器的名称为: "+name);
        return name;
    }

    @Override
    public void jobToBeExecuted(JobExecutionContext context) {
        String name = context.getJobDetail().getKey().getName(); //获取Job的name
        log.info("被监听的job的name是:"+name+"   Scheduler在JobDetail将要被执行时调用的方法");

    }

    @Override
    public void jobExecutionVetoed(JobExecutionContext context) {
        String name = context.getJobDetail().getKey().getName(); //获取Job的name
        log.info("Scheduler在JobDetail即将执行,但又被TriggerListerner否决时会调用的方法");
    }

    @Override
    public void jobWasExecuted(JobExecutionContext context, JobExecutionException e) {
        String name = context.getJobDetail().getKey().getName(); //获取Job的name
        log.info("Scheduler是在JobDetail被执行之后调用这个方法的");
    }
}



上一篇下一篇

猜你喜欢

热点阅读