1. 程式人生 > >添加監聽器listener

添加監聽器listener

port on() context sys author erl ++ key cut

全局註冊,所有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;
    }
}

重啟服務,需要重新添加監聽器。

添加監聽器listener