最近项目中需要用到任务管理,网上搜索后发现很多都是基于1.x版本的,但是最新的2.1.x的版本变更已经很多了,所以记录一个基于2.1.7版本的例子,算是技术积累了。


Maven配置:


    org.quartz-scheduler
    quartz
    2.1.7



任务管理类:

import java.text.ParseException;
import java.util.Collection;
import java.util.Iterator;
import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.Job;
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.SimpleTrigger;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;
import org.quartz.impl.StdSchedulerFactory;
public class QuartzManager {
    private static SchedulerFactory sf = new StdSchedulerFactory();
    private final static String JOB_GROUP_NAME = "defaultGroup_";
    private final static String TRIGGER_GROUP_NAME = "defaultTrigger_";
    private static QuartzManager ins;
    private QuartzManager() {
        super();
    }
    public static QuartzManager instance() {
        if (ins == null) {
            ins = new QuartzManager();
        }
        return ins;
    }
    /**
     * 添加定时任务
     *
     * @param jobName
     *            任务名称
     * @param job
     *            具体的任务执行类
     * @param time
     *            cron表达式
     * @throws SchedulerException
     * @throws ParseException
     */
    public void addJob(String jobName, Job job, String time)
            throws SchedulerException, ParseException {
        Scheduler sched = sf.getScheduler();
        // 任务
        JobDetail jobDetail = JobBuilder.newJob(job.getClass())// 任务执行类
                .withIdentity(jobName, JOB_GROUP_NAME)// 任务名,任务组
                .build();
        // 放入定时任务执行时用到的参数
        jobDetail.getJobDataMap().put("parameters", "TestParameters");
        // 触发器CronTrigger,适用于比较复杂的任务触发,如:每个月的几号的几点几分
         Trigger trigger = TriggerBuilder.newTrigger()
                 .withIdentity(jobName, TRIGGER_GROUP_NAME)
                 .withSchedule(CronScheduleBuilder.cronSchedule(time)).build();
        // SimpleTrigger
        // 适合比较简单的触发。withIntervalInSeconds(15)代表间隔15秒,withRepeatCount(1)代表执行一次
//      Trigger trigger = TriggerBuilder
//              .newTrigger()
//              .withIdentity(jobName, sched.DEFAULT_GROUP)
//              .withSchedule(
//                      SimpleScheduleBuilder.simpleSchedule()
//                              .withIntervalInSeconds(15).withRepeatCount(1))
//              .build();
        sched.scheduleJob(jobDetail, trigger);
        // 启动
        if (!sched.isShutdown())
            sched.start();
    }
    /**
     * 添加定时任务
     *
     * @param jobName
     *            任务名称
     * @param jobGroupName
     *            任务组名称
     * @param triggerName
     *            触发器名称
     * @param triggerGroupName
     *            触发器组名称
     * @param job
     *            具体的任务执行类
     * @param time
     *            cron表达式
     * @throws SchedulerException
     * @throws ParseException
     */
    public void addJob(String jobName, String jobGroupName, String triggerName,
            String triggerGroupName, Job job, String time)
            throws SchedulerException, ParseException {
        Scheduler sched = sf.getScheduler();
        // 任务
        JobDetail jobDetail = JobBuilder.newJob(job.getClass())// 任务执行类
                .withIdentity(jobName, jobGroupName)// 任务名,任务组
                .build();
        // 触发器
        CronTrigger cronTrigger = TriggerBuilder.newTrigger()
                .withIdentity(triggerName, triggerGroupName)
                .withSchedule(CronScheduleBuilder.cronSchedule(time)).build();
        sched.scheduleJob(jobDetail, cronTrigger);
        // 启动
        if (!sched.isShutdown())
            sched.start();
    }
    /**
     * 移除定时任务
     *
     * @param jobName
     *            任务名称
     * @throws SchedulerException
     */
    public void removeJob(String jobName) throws SchedulerException {
        Scheduler sched = sf.getScheduler();
        TriggerKey tk = new TriggerKey(jobName, TRIGGER_GROUP_NAME);
        sched.pauseTrigger(tk);// 停止触发器
        sched.unscheduleJob(tk);// 移除触发器
        JobKey jk = new JobKey(jobName, JOB_GROUP_NAME);
        sched.deleteJob(jk);// 删除任务
    }
    /**
     * 移除定时任务
     *
     * @param jobName
     *            任务名称
     * @param jobGroupName
     *            任务组名称
     * @param triggerName
     *            触发器名称
     * @param triggerGroupName
     *            触发器组名称
     * @throws SchedulerException
     */
    public void removeJob(String jobName, String jobGroupName,
            String triggerName, String triggerGroupName)
            throws SchedulerException {
        Scheduler sched = sf.getScheduler();
        TriggerKey tk = new TriggerKey(triggerName, triggerGroupName);
        sched.pauseTrigger(tk);// 停止触发器
        sched.unscheduleJob(tk);// 移除触发器
        JobKey jk = new JobKey(jobName, jobGroupName);
        sched.deleteJob(jk);// 删除任务
    }
    /**
     * 修改定时任务
     *
     * @param jobName
     *            定时任务名称
     * @param jobGroupName
     *            任务组名称
     * @param triggerName
     *            触发器名称
     * @param triggerGroupName
     *            触发器组名称
     * @param time
     *            cron表达式
     * @throws SchedulerException
     */
    public void modifyJob(String jobName, String jobGroupName,
            String triggerName, String triggerGroupName, String time)
            throws SchedulerException {
        Scheduler sched = sf.getScheduler();
        JobKey jk = new JobKey(jobName, jobGroupName);
        // 任务
        JobDetail jobDetail = sched.getJobDetail(jk);
        removeJob(jobName);
        // 新触发器
        CronTrigger cronTrigger = TriggerBuilder.newTrigger()
                .withIdentity(triggerName, triggerGroupName)
                .withSchedule(CronScheduleBuilder.cronSchedule(time)).build();
        sched.scheduleJob(jobDetail, cronTrigger);
        // 启动
        if (!sched.isShutdown())
            sched.start();
    }
    /**
     * 修改定时任务
     *
     * @param jobName
     *            定时任务名称
     * @param time
     *            触发器cron表达式
     * @throws SchedulerException
     */
    public void modifyJob(String jobName, String time)
            throws SchedulerException {
        Scheduler sched = sf.getScheduler();
        JobKey jk = new JobKey(jobName, JOB_GROUP_NAME);
        // 任务
        JobDetail jobDetail = sched.getJobDetail(jk);
        removeJob(jobName);
        // 新触发器
        CronTrigger cronTrigger = TriggerBuilder.newTrigger()
                .withIdentity(jobName, TRIGGER_GROUP_NAME)
                .withSchedule(CronScheduleBuilder.cronSchedule(time)).build();
        sched.scheduleJob(jobDetail, cronTrigger);
        // 启动
        if (!sched.isShutdown())
            sched.start();
    }
    /**
     * 移除所有定时任务
     *
     * @throws SchedulerException
     */
    public void removeAll() throws SchedulerException {
        Collection list = sf.getAllSchedulers();
        Iterator it = list.iterator();
        while (it.hasNext()) {
            Scheduler sc = it.next();
            if (sc != null) {
                sc.clear();
            }
        }
    }
}


具体的任务执行类:

import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
public class TestJob implements Job {
    // 判断作业是否执行的旗标
    private boolean isRunning = false;
    public void execute(JobExecutionContext context)
            throws JobExecutionException {
        JobDataMap dataMap = context.getJobDetail().getJobDataMap();
        System.out.println("TestJob作业被调度。任务名称:"+context.getTrigger().getKey().getName()
                + ",使用到的参数:"+dataMap.getString("parameters")+",执行时间:" + System.currentTimeMillis());
    }
}


测试主函数类:

public class JobTestMain {
    public static void main(String[] args) {
        TestJob job = new TestJob();
            String job_name ="test";
            try {
                for(int i=0;i<2;i++){
                     System.out.println("----添加定时任务(5秒)----");
                     QuartzManager.instance().addJob(job_name+i,job,"0/5 * * * * ?");
                     Thread.sleep(10000);
                                                                                           
                     System.out.println("----移除定时任务(5秒)----");
                     QuartzManager.instance().removeJob(job_name+i);
                     Thread.sleep(10000);
                                                                                           
                     System.out.println("----添加定时任务(10秒)----");
                     QuartzManager.instance().addJob(job_name+i,job,"0/10 * * * * ?");
                     Thread.sleep(10000);
                     System.out.println("----修改定时任务(更改10为3秒)----");
                     QuartzManager.instance().modifyJob(job_name+i,"0/3 * * * * ?");
                }
                Thread.sleep(10000);
                System.out.println("----清空所有定时任务----");
                QuartzManager.instance().removeAll();
            }  catch (Exception e) {
                e.printStackTrace();
            }
    }
}


cron表达式介绍:http://blog.csdn.net/yuan8080/article/details/6583603