在spring中实现quartz的动态调度(开始、暂停、停止等)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/fantasic_van/article/details/74942062

需求: 需要在页面设定某个时间,然后点击按钮后,执行某个调度,并且可以在页面删除某个调度

1、导包


    org.quartz-scheduler
    quartz
    2.2.1


    org.quartz-scheduler
    quartz-jobs
    2.2.1

2、创建QuartzManager类,管理job

import org.apache.commons.lang.StringUtils;
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.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;

public class QuartzManager {

    private Scheduler scheduler;

    /**
     * @Description: 添加一个定时任务
     * 
     * @param jobName
     *            任务名
     * @param jobGroupName
     *            任务组名
     * @param triggerName
     *            触发器名
     * @param triggerGroupName
     *            触发器组名
     * @param jobClass
     *            任务
     * @param cron
     *            时间设置,参考quartz说明文档
     */
    @SuppressWarnings({ "unchecked", "rawtypes" })
    public void addJob(String jobName, String jobGroupName, String triggerName, String triggerGroupName, Class jobClass,
            String cron) {
        try {
            // 任务名,任务组,任务执行类
            JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(jobName, jobGroupName).build();

            // 触发器
            TriggerBuilder triggerBuilder =   TriggerBuilder.newTrigger();
            // 触发器名,触发器组
            triggerBuilder.withIdentity(triggerName, triggerGroupName);
            triggerBuilder.startNow();
            // 触发器时间设定
            triggerBuilder.withSchedule(CronScheduleBuilder.cronSchedule(cron));
            // 创建Trigger对象
            CronTrigger trigger = (CronTrigger) triggerBuilder.build();

            // 调度容器设置JobDetail和Trigger
            scheduler.scheduleJob(jobDetail, trigger);

            // 启动
            if (!scheduler.isShutdown()) {
                scheduler.start();
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * @Description: 修改一个任务的触发时间
     * 
     * @param jobName
     * @param jobGroupName
     * @param triggerName
     *            触发器名
     * @param triggerGroupName
     *            触发器组名
     * @param cron
     *            时间设置,参考quartz说明文档
     */
    public void modifyJobTime(String jobName, String jobGroupName, String triggerName, String triggerGroupName,
            String cron) {
        try {
            TriggerKey triggerKey = TriggerKey.triggerKey(triggerName, triggerGroupName);
            CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
            if (trigger == null) {
                return;
            }

            String oldTime = trigger.getCronExpression();
            if (!oldTime.equalsIgnoreCase(cron)) {
                /** 方式一 :调用 rescheduleJob 开始 */
                // 触发器
                TriggerBuilder triggerBuilder = TriggerBuilder.newTrigger();
                // 触发器名,触发器组
                triggerBuilder.withIdentity(triggerName, triggerGroupName);
                triggerBuilder.startNow();
                // 触发器时间设定
                triggerBuilder.withSchedule(CronScheduleBuilder.cronSchedule(cron));
                // 创建Trigger对象
                trigger = (CronTrigger) triggerBuilder.build();
                // 方式一 :修改一个任务的触发时间
                scheduler.rescheduleJob(triggerKey, trigger);
                /** 方式一 :调用 rescheduleJob 结束 */

                /** 方式二:先删除,然后在创建一个新的Job */
                // JobDetail jobDetail =
                // scheduler.getJobDetail(JobKey.jobKey(jobName, jobGroupName));
                // Class jobClass = jobDetail.getJobClass();
                // removeJob(jobName, jobGroupName, triggerName,
                // triggerGroupName);
                // addJob(jobName, jobGroupName, triggerName, triggerGroupName,
                // jobClass, cron);
                /** 方式二 :先删除,然后在创建一个新的Job */
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * @Description: 移除一个任务
     * 
     * @param jobName
     * @param jobGroupName
     * @param triggerName
     * @param triggerGroupName
     */
    public void removeJob(String jobName, String jobGroupName, String triggerName, String triggerGroupName) {
        try {
            TriggerKey triggerKey = TriggerKey.triggerKey(triggerName, triggerGroupName);

            scheduler.pauseTrigger(triggerKey);// 停止触发器
            scheduler.unscheduleJob(triggerKey);// 移除触发器
            scheduler.deleteJob(JobKey.jobKey(jobName, jobGroupName));// 删除任务
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * @Description:启动所有定时任务
     */
    public void startJobs() {
        try {
            scheduler.start();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * @Description:关闭所有定时任务
     */
    public void shutdownJobs() {
        try {
            if (!scheduler.isShutdown()) {
                scheduler.shutdown();
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public Scheduler getScheduler() {
        return scheduler;
    }

    public void setScheduler(Scheduler scheduler) {
        this.scheduler = scheduler;
    }

    public String transCron(String time){
        String seconds = StringUtils.substringAfterLast(time, ":");
        String minute = StringUtils.substringAfter(time, ":").substring(0, 2);
        String hour = StringUtils.substringAfter(time, " ").substring(0, 2);
        String day = StringUtils.substringAfterLast(time, "-").substring(0, 2);
        String month =  StringUtils.substringAfter(time, "-").substring(0, 2);
        return seconds + " " + minute + " " + hour + " " + day + " " + month + " ?";
    }
}

3、MyJob类,实现自己的调度业务,该类必须实现Job接口

package cn.tisson.qoe.quartz;

import java.util.Map;

import javax.annotation.Resource;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.tisson.qoe.utils.ApacheFtpUtil;
import cn.tisson.qoe.utils.CallShellUtil;

public class MyJob implements Job{

    private Logger logger = LoggerFactory.getLogger(MyJob.class);

    //直接注入  
    @Resource
    private QuartzManager quartzManager;

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        try {
            test();
            downloadYZfile(); 
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void test() throws Exception{
        logger.info("【test】动态定时调度测试");
    }

    /**
     * 同步光宽转化率月清单
     * @throws Exception
     */
    public void downloadYZfile() throws Exception{
        //自己的业务逻辑在这里实现
    }
}

 

4、在springmvc的配置文件,添加配置

  
       
           
             
           
       
   

  
       
      
   

5、在Controller中

    //这个bean在spring中配置,可以直接注入
    @Resource
    private QuartzManager quartzManager;

    @RequestMapping(value = "startQuartz", method = {RequestMethod.GET})
    @ResponseBody
    public String testQuartz(String quartzTime) throws Exception{
        logger.info("===========开始执行调度=========时间为 " + quartzTime);
        String cronStr = quartzManager.transCron(quartzTime);
        logger.info("======cron表达式========" + cronStr);
        quartzManager.addJob("test", "test", "test", "test", MyJob.class, cronStr);    
        //quartzManager.modifyJobTime("test", "test", "test", "test", "0 50 10 * * ?");    
        //quartzManager.removeJob("test", "test", "test", "test");    
        //quartzManager.shutdownJobs();
        return "success";
    }

    @RequestMapping(value = "stopQuartz", method = {RequestMethod.GET})
    @ResponseBody
    public String shutDownQuartz() throws Exception{
        logger.info("===========关闭调度test==================");
        quartzManager.removeJob("test", "test", "test", "test");  
        return "关闭成功";
    }

因为需求是要配置时间执行调度,所以不能控制执行次数,如果需要控制执行次数,可以使用
triggerBuilder.withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(1).withRepeatCount(1));//执行间隔和重复执行的次数
该方法参考链接: http://www.2cto.com/kf/201608/533723.html

最后,附上参考的博主链接:
http://blog.csdn.net/xlxxcc/article/details/52118102

你可能感兴趣的:(工具类)