绝对原创(quartz)

/* 
 * Copyright (c) 2014, S.F. Express Inc. All rights reserved.
 */
package com.sf.demo.util;

/**
 * 描述:
 * 
 * <pre>HISTORY
 * ****************************************************************************
 *  ID   DATE           PERSON          REASON
 *  1    2014-9-9      sfit0272         Create
 * ****************************************************************************
 * </pre>
 * @author sfit0272
 * @since 
 */
import java.util.Date;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.log4j.Logger;
import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.SimpleScheduleBuilder;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;
import org.quartz.impl.StdSchedulerFactory;
 
/**
 * 定时器任务调度管理器
 *
 * @author
 */
public class QuartzManager {
 
    private final String jobGroupName;
    private final String triggerGroupName;
    private Scheduler sched;
    private final static SchedulerFactory sf = new StdSchedulerFactory();
    private final static Map<String, QuartzManager> instanceMap = new ConcurrentHashMap<String, QuartzManager>();
 
    private final static Logger logger = Logger.getLogger(QuartzManager.class);
 
    /**
     * 构造方法,外部不能实例化
     *
     * @param jobGroupName 工作组名
     * @param triggerGroupName 触发器组名
     */
    private QuartzManager(String jobGroupName, String triggerGroupName) {
        this.jobGroupName = jobGroupName;
        this.triggerGroupName = triggerGroupName;
    }
 
    /**
     * 获取调度器
     *
     * @return 定时调度器
     * @throws SchedulerException 调度器内部执行异常
     */
    private Scheduler getScheduler() throws SchedulerException {
        if (sched == null) {
            sched = sf.getScheduler();
            //sched.getListenerManager().addTriggerListener(new QuartzTriggerListener());
            //sched.getListenerManager().addSchedulerListener(new QuartzSchedulerListener(sched));
        }
        return sched;
    }
 
    /**
     * 获取一个定时调度管理器
     *
     * @param jobGroupName 工作组名
     * @param triggerGroupName 触发器组名
     * @return 定时调度管理器
     */
    public static QuartzManager getInstance(String jobGroupName, String triggerGroupName) {
        String instanceKey = jobGroupName + "_" + triggerGroupName;
        if (instanceMap.containsKey(instanceKey)) {
            return instanceMap.get(instanceKey);
        }
        QuartzManager manager = new QuartzManager(jobGroupName, triggerGroupName);
        instanceMap.put(instanceKey, manager);
        return manager;
    }
 
    /**
     * 获取一个定时调度管理器
     *
     * @param groupName 工作组名和触发器组名相同
     * @return 定时调度管理器
     */
    public static QuartzManager getInstance(String groupName) {
        return getInstance(groupName, groupName);
    }
 
    /**
     * 关闭调度器
     *
     * @param waitForJobsToComplete 是否等候所有工作被调度完成后再关闭
     */
    public void shutdown(boolean waitForJobsToComplete) {
        String instanceKey = jobGroupName + "_" + triggerGroupName;
        if (instanceMap.containsKey(instanceKey)) {
            QuartzManager manager = instanceMap.get(instanceKey);
            if (manager != null && manager.sched != null) {
                try {
                    manager.sched.shutdown(waitForJobsToComplete);
                } catch (SchedulerException ex) {
                    logger.debug(ex.getLocalizedMessage(), ex);
                }
            }
        }
    }
 
    /**
     * 关闭调度器
     */
    public void shutdown() {
        shutdown(false);
    }
     
    /**
     * 添加一个调度任务
     *
     * @param jobName 任务名
     * @param cls 任务类型
     * @param start 任务执行的开始时间,null表示立刻执行
     * @param end 任务执行的结束时间,null表示任务在执行repeat次数后自动结束
     * @param jobBindData 绑定到job中的数据,可为null
     * @param intervalType 任务执行时间间隔类型,1、毫秒,2、秒,3、分,4、小时,默认为2
     * @param intervalValue 任务执行时间间隔
     * @param repeat 任务执行次数,0表示执行一次,实际执行次数为此值+1
     * @throws SchedulerException
     */
    public void addJob(String jobName, Class cls, Date start, Date end, Map<String, Object> jobBindData, int intervalType, long intervalValue, int repeat) throws SchedulerException {
    	JobDetail jobDetail = JobBuilder.newJob(cls).withIdentity(jobName, jobGroupName).build();
        if (jobBindData != null) {
            for (Entry<String, Object> entry : jobBindData.entrySet()) {
                jobDetail.getJobDataMap().put(entry.getKey(), entry.getValue());
            }
        }
        SimpleScheduleBuilder simpleScheduleBuilder = SimpleScheduleBuilder.simpleSchedule();
        switch (intervalType) {
            case 1:
                //毫秒
                simpleScheduleBuilder.withIntervalInMilliseconds(intervalValue);
                break;
            case 3:
                //分
                simpleScheduleBuilder.withIntervalInMinutes((int) intervalValue);
                break;
            case 4:
                //时
                simpleScheduleBuilder.withIntervalInHours((int) intervalValue);
                break;
            default:
                //秒
                simpleScheduleBuilder.withIntervalInSeconds((int) intervalValue);
                break;
        }
        if(repeat >= 0) {
            simpleScheduleBuilder.withRepeatCount(repeat);
        }
        TriggerBuilder<org.quartz.Trigger> builder = TriggerBuilder.newTrigger()
                .withIdentity(jobName, triggerGroupName);
        if (start == null) {
            builder.startNow();
        } else {
            builder.startAt(start);
        }
        if (end != null) {
            builder.endAt(end);
        }
        Trigger trigger = builder.withSchedule(simpleScheduleBuilder).build();
        Scheduler scheduler = getScheduler();
        scheduler.scheduleJob(jobDetail, trigger);
        if (!scheduler.isShutdown()) {
            scheduler.start();
        }
    }
     
    /**
     * 添加一个调度任务,在start时间执行一次
     * @param jobName 任务名
     * @param cls 任务类型
     * @param start 任务执行的开始时间,null表示立刻执行
     * @param end 任务执行的结束时间,null表示任务在执行repeat次数后自动结束
     * @param jobBindData 绑定到job中的数据,可为null
     * @throws SchedulerException 
     */
    public void addJob(String jobName, Class cls, Date start , Date end, Map<String, Object> jobBindData) throws SchedulerException {
        this.addJob(jobName, cls, start, end, jobBindData, 2, 1, 0);
    }
     
    /**
     * 添加一个调度任务,在start时间执行一次
     * @param jobName 任务名
     * @param cls 任务类型
     * @param start 任务执行的开始时间,null表示立刻执行
     * @param jobBindData 绑定到job中的数据,可为null
     * @throws SchedulerException 
     */
    public void addJob(String jobName, Class cls, Date start, Map<String, Object> jobBindData) throws SchedulerException {
        this.addJob(jobName, cls, start, null, jobBindData);
    }
 
    /**
     * 添加一个定时任务,使用默认的任务组名,触发器名,触发器组名
     *
     * @param jobName 任务名
     * @param cls
     * @param time 时间设置,参考quartz说明文档
     * @throws SchedulerException 调度器内部执行异常
     */
    public void addJob(String jobName, Class cls, String time) throws SchedulerException {
        JobDetail jobDetail = JobBuilder.newJob(cls).withIdentity(jobName, jobGroupName).build();
        CronTrigger trigger = TriggerBuilder.newTrigger()
                .withIdentity(jobName, triggerGroupName)//触发器名,触发器组
                .withSchedule(CronScheduleBuilder.cronSchedule(time))
                .build();
        Scheduler scheduler = getScheduler();
        scheduler.scheduleJob(jobDetail, trigger);
        if (!scheduler.isShutdown()) {
            scheduler.start();
        }
    }
 
    /**
     * 移除一个任务
     *
     * @param triggerKey 触发器键
     * @param jobKey 工作任务键
     * @throws SchedulerException 调度器内部执行异常
     */
    public void removeJob(TriggerKey triggerKey, JobKey jobKey) throws SchedulerException {
        Scheduler scheduler = getScheduler();
        scheduler.pauseTrigger(triggerKey);
        scheduler.unscheduleJob(triggerKey);
        scheduler.deleteJob(jobKey);
    }
 
    /**
     * 移除一个任务(使用默认的任务组名,触发器名,触发器组名)
     *
     * @param jobName 工作任务名
     * @throws SchedulerException 调度器内部执行异常
     */
    public void removeJob(String jobName) throws SchedulerException {
        TriggerKey triggerKey = new TriggerKey(jobName, triggerGroupName);
        JobKey jobKey = new JobKey(jobName, jobGroupName);
        removeJob(triggerKey, jobKey);
    }
}

你可能感兴趣的:(quartz)