Quartz 系统(一) :实现定时作业调度

注:之前实现的单节点任务调度
1、本代码实现任务的启动停止恢复功能
2、任务是页面上增加,时间策略也是页面增加,保存在表中
3、ScheduleJob 即为任务类
4、在其他模块中进行调用此类
5、quartz版本1.8  spring 3.0

public class QuartzManager {

    private static Logger logger = Logger.getLogger(QuartzManager.class);

    private static SchedulerFactory gSchedulerFactory = new StdSchedulerFactory();
    private static String JOB_GROUP_NAME = "BIGDATA_JOBGROUP_NAME";
    private static String TRIGGER_GROUP_NAME = "BIGDATA_TRIGGERGROUP_NAME";

    /**
     * @Description: 添加一个定时任务,使用默认的任务组名,触发器名,触发器组名
     *
     * @param jobName
     *            任务名
     * @param cls
     *            任务
     * @param time
     *            时间设置,参考quartz说明文档
     * @throws Throwable
     */
    @SuppressWarnings("unchecked")
    public static void addJob(ScheduleJob job) throws Exception {
        try {
            addJob(job.getJobid(), JOB_GROUP_NAME, job.getJobid(), TRIGGER_GROUP_NAME,job, job.getCronExpression());
        }catch(SchedulerException e){
            e.printStackTrace();
            if(e.getMessage().contains("the given trigger will never fire")){
                throw new SchedulerException("任务配置错误[此配置时间过期]!");
            }
        }catch (Exception e) {
            e.printStackTrace();
            throw new Exception("异常:"+e.getMessage());
        }
    }

    /**
     * @Description: 添加一个定时任务
     *
     * @param jobName
     *            任务名
     * @param jobGroupName
     *            任务组名
     * @param triggerName
     *            触发器名
     * @param triggerGroupName
     *            触发器组名
     * @param jobClass
     *            任务
     * @param time
     *            时间设置,参考quartz说明文档
     * @throws ClassNotFoundException
     * @throws ParseException
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    private static void addJob(String jobName, String jobGroupName,
            String triggerName, String triggerGroupName, ScheduleJob job,
            String time) throws SchedulerException, ClassNotFoundException, ParseException {
           
            logger.info("-------启动任务方法----");
            Scheduler sched = gSchedulerFactory.getScheduler();
            logger.info("-------------需要运行的任务类为:"+job.getJobclass());
            if(job.getJobclass()==null){
                throw new SchedulerException("没有配置任务执行类!");
            }
            Class c = Class.forName(job.getJobclass());
            JobDetail jobDetail = new JobDetail(jobName, jobGroupName, c);// 任务名,任务组,任务执行类
           
            jobDetail.getJobDataMap().put("scheduleJob", job);  //任务参数
            // 触发器
            CronTrigger trigger = new CronTrigger(triggerName, triggerGroupName);// 触发器名,触发器组
            SimpleDateFormat sdf = new SimpleDateFormat();
            if(job.getStartTime()!=null){
                String startt= job.getStartTime();
                if(startt.length()==4){
                    //yyyy
                    sdf.applyPattern("yyyy");
                }else if(startt.length()==7){
                    //yyyy-MM
                    sdf.applyPattern("yyyy-MM");
                }else if(startt.length()==10){
                    //yyyy-MM-dd
                    sdf.applyPattern("yyyy-MM-dd");
                }else{
                    //不存在开始时间
                }
                trigger.setStartTime(sdf.parse(startt));
            }
            if(job.getEndTime()!=null){
                String endt= job.getEndTime();
                if(endt.length()==4){
                    //yyyy
                    sdf.applyPattern("yyyy");
                }else if(endt.length()==7){
                    //yyyy-MM
                    sdf.applyPattern("yyyy-MM");
                }else if(endt.length()==10){
                    //yyyy-MM-dd
                    sdf.applyPattern("yyyy-MM-dd");
                }else{
                    //不存在开始时间
                }
                trigger.setEndTime(sdf.parse(endt));
            }
           
            trigger.setCronExpression(time);// 触发器时间设定
            sched.scheduleJob(jobDetail, trigger);
            // 启动
            if (!sched.isStarted()) {
                sched.start();
            }
    }
    public static void addJob(String jobName,Class clz,
            String time) throws Exception {
        try {
            Scheduler sched = gSchedulerFactory.getScheduler();
            logger.info("-------------需要运行的任务类为:"+clz);
            JobDetail jobDetail = new JobDetail(jobName, JOB_GROUP_NAME, clz);// 任务名,任务组,任务执行类
           
            // 触发器
            CronTrigger trigger = new CronTrigger(jobName, TRIGGER_GROUP_NAME);// 触发器名,触发器组
            trigger.setCronExpression(time);// 触发器时间设定
            sched.scheduleJob(jobDetail, trigger);
            // 启动
            if (!sched.isStarted()) {
                sched.start();
            }
        } catch (Exception e) {
            throw new Exception(e);
        }
    }
    /**
     * @Description: 修改一个任务的触发时间(使用默认的任务组名,触发器名,触发器组名)
     *
     * @param jobName
     * @param time
     * @throws Exception
     *
     */
    @SuppressWarnings("unchecked")
    public static void modifyJobTime(String jobName, String time) throws Exception {
        try {
            Scheduler sched = gSchedulerFactory.getScheduler();
            CronTrigger trigger = (CronTrigger) sched.getTrigger(jobName,
                    TRIGGER_GROUP_NAME);
            if (trigger == null) {
                return;
            }
            String oldTime = trigger.getCronExpression();
            if (!oldTime.equalsIgnoreCase(time)) {
                JobDetail jobDetail = sched.getJobDetail(jobName,
                        JOB_GROUP_NAME);
                Class objJobClass = jobDetail.getJobClass();
                removeJob(jobName);
                addJob(jobName, objJobClass, time);
            }
        } catch (Exception e) {
            throw new Exception(e);
        }
    }

    /**
     * @Description: 修改一个任务的触发时间
     *
     * @param triggerName
     * @param triggerGroupName
     * @param time
     * @throws Exception
     */
    public static void modifyJobTime(String triggerName,
            String triggerGroupName, String time) throws Exception {
        try {
            Scheduler sched = gSchedulerFactory.getScheduler();
            CronTrigger trigger = (CronTrigger) sched.getTrigger(triggerName,
                    triggerGroupName);
            if (trigger == null) {
                return;
            }
            String oldTime = trigger.getCronExpression();
            if (!oldTime.equalsIgnoreCase(time)) {
                CronTrigger ct = (CronTrigger) trigger;
                // 修改时间
                ct.setCronExpression(time);
                // 重启触发器
                sched.resumeTrigger(triggerName, triggerGroupName);
            }
        } catch (Exception e) {
            throw new Exception(e);
        }
    }

    /**
     * @Description: 移除一个任务(使用默认的任务组名,触发器名,触发器组名)
     *
     * @param jobName
     * @throws Exception
     *
     */
    public static void removeJob(String jobName) throws Exception {
        removeJob(jobName, JOB_GROUP_NAME, jobName, TRIGGER_GROUP_NAME);
    }

    /**
     * @Description: 移除一个任务
     *
     * @param jobName
     * @param jobGroupName
     * @param triggerName
     * @param triggerGroupName
     * @throws Exception
     *
     */
    public static void removeJob(String jobName, String jobGroupName,
            String triggerName, String triggerGroupName) throws Exception {
        try {
            Scheduler sched = gSchedulerFactory.getScheduler();
            sched.pauseTrigger(triggerName, triggerGroupName);// 停止触发器
            sched.unscheduleJob(triggerName, triggerGroupName);// 移除触发器
            sched.deleteJob(jobName, jobGroupName);// 删除任务
        } catch (Exception e) {
            throw new Exception(e);
        }
    }
    /**
     * @Description: 暂停一个任务
     *
     * @param jobName
     * @param jobGroupName
     * @param triggerName
     * @param triggerGroupName
     * @throws Exception
     *
     */
    public static void pauseJob(String jobName) throws Exception {
        pauseJob(jobName, JOB_GROUP_NAME, jobName, TRIGGER_GROUP_NAME);
    }
    public static void pauseJob(String jobName, String jobGroupName,
            String triggerName, String triggerGroupName) throws Exception {
        try {
            Scheduler sched = gSchedulerFactory.getScheduler();
            sched.pauseTrigger(triggerName, triggerGroupName);// 停止触发器
//            sched.pauseJob(jobName, jobGroupName);
           
            // 启动
            if (!sched.isStarted()) {
                logger.info("暂停任务后,没有启动,启动调度器");
                sched.start();
            }
        } catch (Exception e) {
            throw new Exception(e);
        }
    }
   
    /**
     * 恢复暂停的任务
     * @param triggerName
     * @param triggerGroupName
     * @param time
     * @throws Exception
     */
    public static void resumeStopJob(String jobName) throws Exception {
        resumeStopJob(jobName, JOB_GROUP_NAME, jobName, TRIGGER_GROUP_NAME);
    }
    public static void resumeStopJob(String jobName, String jobGroupName,
            String triggerName, String triggerGroupName) throws Exception {
        try {
            logger.info("恢复被暂停的任务!");
            Scheduler sched = gSchedulerFactory.getScheduler();
//            CronTrigger trigger = (CronTrigger) sched.getTrigger(triggerName,
//                    triggerGroupName);
//            JobDetail job = sched.getJobDetail(jobName, jobGroupName);
            sched.resumeTrigger(triggerName, triggerGroupName);
//            sched.resumeJob(jobName, jobGroupName);
       
//            if(job!=null){
//                logger.info("存在此任务!");
////                sched.resumeJob(jobName, jobName);
//            }
            if (!sched.isStarted()) {
                logger.info("恢复任务后,没有启动,启动调度器");
                sched.start();
            }
            logger.info("恢复此任务!"+jobName);
        } catch (Exception e) {
            throw new Exception(e);
        }
    }
    /**
     * @throws Exception
     * @Description:启动所有定时任务
     *
     */
    public static void startJobs() throws Exception {
        try {
            Scheduler sched = gSchedulerFactory.getScheduler();
            sched.start();
        } catch (Exception e) {
            throw new Exception(e);
        }
    }

    /**
     * @throws Exception
     * @Description:关闭所有定时任务
     *
     */
    public static void shutdownJobs() throws Exception {
        try {
            Scheduler sched = gSchedulerFactory.getScheduler();
            if (!sched.isShutdown()) {
                sched.shutdown();
            }
        } catch (Exception e) {
            throw new Exception(e);
        }
    }
    /**
     * @throws Exception
     * @Description:关闭某个定时任务
     *
     */
    public static void shutdownJob(String jobname) throws Exception {
        try {
            logger.info("关闭此任务!");
            Scheduler sched = gSchedulerFactory.getScheduler();
            sched.deleteJob(jobname, JOB_GROUP_NAME);
            logger.info("关闭此任务!"+jobname);
        } catch (Exception e) {
            throw new Exception(e);
        }
    }
    /**
     * @throws Exception
     * @Description:暂停所有定时任务
     *
     */
    public static void pauseAllJobs() throws Exception {
        try {
            Scheduler sched = gSchedulerFactory.getScheduler();
            sched.pauseAll();
        } catch (Exception e) {
            throw new Exception(e);
        }
    }

    public static void main(String[] args) {
        try {
            String job_name = "动态任务调度";
            System.out.println("【系统启动】开始(每1秒输出一次)...");
            QuartzManager.addJob(job_name, QuartzJobFactory.class, "0/1 * * * * ?");

            Thread.sleep(5000);
            System.out.println("【修改时间】开始(每2秒输出一次)...");
            QuartzManager.modifyJobTime(job_name, "10/2 * * * * ?");
            Thread.sleep(6000);
            System.out.println("【移除定时】开始...");
            QuartzManager.removeJob(job_name);
            System.out.println("【移除定时】成功");

            System.out.println("【再次添加定时任务】开始(每10秒输出一次)...");
            QuartzManager.addJob(job_name, QuartzJobFactory.class, "*/10 * * * * ?");
            Thread.sleep(60000);
            System.out.println("【移除定时】开始...");
            QuartzManager.removeJob(job_name);
            System.out.println("【移除定时】成功");
           
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

 

 



你可能感兴趣的:(quartz)