第十壹本書每天写1000字写作新生

分布式定时任务(三)

2016-09-20  本文已影响2169人  lyndon_nfc

Quartz分布式定时任务的暂停和恢复等:

前两篇我们了解了quartz分布式定时任务的基本原理和实现方式,知道所有的定时任务都会被持久化到数据库。那么我们肯定可以通过操作数据库来做定时任务的暂停,恢复,立即启动,添加等操作。
事实上,quartz已经给我们提供来一些列的api接口来操作对应的定时任务,我们只需要在这个基础之上做进一步的扩展和封装就可以实现我们自己业务,下面,将围绕定时任务的控制,提供一个简单的实现方式。

使用的环境版本:spring4.x+quartz2.2.x

1,首先,我们需要创建一个我们自己job的实体类ScheduleJob:

/** 
* Created by lyndon on 16/9/13. * job的实体类
 */
public class ScheduleJob {   

        private String jobNo; //任务编号    
        private String jobName; //任务名称    
        private String jobGroup; //任务所属组    
        private String desc; //任务描述          
        private String jobStatus; //任务状态    
        private String cronExpression; //任务对应的时间表达式
        private String triggerName; //触发器名称

         //此处省略get和set方法
  }

2, 创建我们自己的QuartzImplService服务层:



import org.quartz.*;
import org.quartz.impl.matchers.GroupMatcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * Created by lyndon on 16/9/13.
 * quartz_job的工具类
 */
@Service
public class QuartzUtils {

    private final Logger logger = LoggerFactory.getLogger(QuartzUtils.class);

    @Resource
    private Scheduler scheduler;


    /**
     *
     * 获取计划任务列表
     * @return  List<ScheduleJob>
     */
    public List<ScheduleJob> getPlanJobList() throws SchedulerException{
        List<ScheduleJob> jobList = new ArrayList<>();
        GroupMatcher<JobKey> matcher = GroupMatcher.anyJobGroup();
        Set<JobKey> jobKeys = scheduler.getJobKeys(matcher);;
        jobKeys = scheduler.getJobKeys(matcher);
        for (JobKey jobKey : jobKeys) {
            List<? extends Trigger> triggers = scheduler.getTriggersOfJob(jobKey);
            for (Trigger trigger : triggers) {
                ScheduleJob job = new ScheduleJob();
                job.setJobName(jobKey.getName());
                job.setJobGroup(jobKey.getGroup());
                // 此处是我自己业务需要,给每个定时任务配置类对应的编号和描述
                String value = PropertiesUtils.getStringCN(jobKey.getName());
                if(null != value && !"".equals(value)){
                    job.setJobNo(value.split("/")[0]);
                    job.setDesc(value.split("/")[1]);
                }else{
                    job.setJobNo("0000");
                    job.setDesc("未监控任务");
                }
                job.setTriggerName("触发器:" + trigger.getKey());
                Trigger.TriggerState triggerState = scheduler.getTriggerState(trigger.getKey());
                job.setJobStatus(triggerState.name());
                if (trigger instanceof CronTrigger) {
                    CronTrigger cronTrigger = (CronTrigger) trigger;
                    String cronExpression = cronTrigger.getCronExpression();
                    job.setCronExpression(cronExpression);
                }
                jobList.add(job);
            }
        }
      // 对返回的定时任务安装编号做排序
        Collections.sort(jobList,new Comparator<ScheduleJob>(){
            public int compare(ScheduleJob arg0, ScheduleJob arg1) {
                return arg0.getJobNo().compareTo(arg1.getJobNo());
            }
        });

        return jobList;
    }


    /**
     * 获取正在运行的任务列表
     * @return List<ScheduleJob>
     */
    public List<ScheduleJob> getCurrentJobList() throws SchedulerException{
        List<JobExecutionContext> executingJobs = scheduler.getCurrentlyExecutingJobs();;
        List<ScheduleJob> jobList = new ArrayList<ScheduleJob>(executingJobs.size());;
        for (JobExecutionContext executingJob : executingJobs) {
            ScheduleJob job = new ScheduleJob();
            JobDetail jobDetail = executingJob.getJobDetail();
            JobKey jobKey = jobDetail.getKey();
            Trigger trigger = executingJob.getTrigger();
            job.setJobName(jobKey.getName());
            job.setJobGroup(jobKey.getGroup());
            String value = PropertiesUtils.getStringCN(jobKey.getName());
            if(null != value && !"".equals(value)){
                job.setJobNo(value.split("/")[0]);
                job.setDesc(value.split("/")[1]);
            }else{
                job.setJobNo("0000");
                job.setDesc("未监控任务");
            }
            job.setTriggerName("触发器:" + trigger.getKey());
            Trigger.TriggerState triggerState = scheduler.getTriggerState(trigger.getKey());
            job.setJobStatus(triggerState.name());
            if (trigger instanceof CronTrigger) {
                CronTrigger cronTrigger = (CronTrigger) trigger;
                String cronExpression = cronTrigger.getCronExpression();
                job.setCronExpression(cronExpression);
            }
            jobList.add(job);
        }
        Collections.sort(jobList,new Comparator<ScheduleJob>(){
            public int compare(ScheduleJob arg0, ScheduleJob arg1) {
                return arg0.getJobNo().compareTo(arg1.getJobNo());
            }
        });
        return  jobList;
    }

    /**
     * 暂停当前任务
     * @param scheduleJob
     */
    public void pauseJob(ScheduleJob scheduleJob) throws SchedulerException{
        JobKey jobKey = JobKey.jobKey(scheduleJob.getJobName(), scheduleJob.getJobGroup());
        if(scheduler.checkExists(jobKey)){
            scheduler.pauseJob(jobKey);
        }
    }

    /**
     * 恢复当前任务
     * @param scheduleJob
     */
    public void resumeJob(ScheduleJob scheduleJob) throws SchedulerException{
        JobKey jobKey = JobKey.jobKey(scheduleJob.getJobName(), scheduleJob.getJobGroup());

        if(scheduler.checkExists(jobKey)){
            //并恢复
            scheduler.resumeJob(jobKey);
            //重置当前时间
            this.rescheduleJob(scheduleJob);
        }
    }

    /**
     * 删除任务
     * @param scheduleJob
     * @return boolean
     */
    public boolean deleteJob(ScheduleJob scheduleJob) throws SchedulerException{
        JobKey jobKey = JobKey.jobKey(scheduleJob.getJobName(), scheduleJob.getJobGroup());
        if(scheduler.checkExists(jobKey)){
            return scheduler.deleteJob(jobKey);
        }
        return false;

    }

    /**
     * 立即触发当前任务
     * @param scheduleJob
     */
    public void triggerJob(ScheduleJob scheduleJob) throws SchedulerException{
        JobKey jobKey = JobKey.jobKey(scheduleJob.getJobName(), scheduleJob.getJobGroup());
        if(scheduler.checkExists(jobKey)){
            scheduler.triggerJob(jobKey);
        }

    }

    /**
     * 更新任务的时间表达式
     * @param scheduleJob
     * @return Date
     */
    public Date rescheduleJob(ScheduleJob scheduleJob) throws SchedulerException{
        TriggerKey triggerKey = TriggerKey.triggerKey(scheduleJob.getJobName(),
                scheduleJob.getJobGroup());
        if(scheduler.checkExists(triggerKey)){
            CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(scheduleJob
                    .getCronExpression());
            //按新的cronExpression表达式重新构建trigger
            trigger = trigger.getTriggerBuilder().withIdentity(triggerKey)
                    .withSchedule(scheduleBuilder).build();
            //按新的trigger重新设置job执行
            return scheduler.rescheduleJob(triggerKey, trigger);
        }
        return null;
    }

    /**
     * 查询其中一个任务的状态
     * @param scheduleJob
     * @return
     * @throws SchedulerException
     */
    public String scheduleJob(ScheduleJob scheduleJob) throws SchedulerException {
        String status = null;
        TriggerKey triggerKey = TriggerKey.triggerKey(scheduleJob.getJobName(), scheduleJob.getJobGroup());
        CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
        if (null != trigger) {
            Trigger.TriggerState triggerState = scheduler.getTriggerState(trigger.getKey());
            status = triggerState.name();
        }
        return status;
    }

    /**
     * 校验job是否已经加载
     * @param scheduleJob  JOB基本信息参数
     * @return          是否已经加载
     */
    public boolean checkJobExisted(ScheduleJob scheduleJob) throws SchedulerException {
        return scheduler.checkExists(new JobKey(scheduleJob.getJobName(), scheduleJob.getJobGroup()));
    }

  
    private String getStatuDesc(String status){
        if(status.equalsIgnoreCase("NORMAL")){
            return "正常";
        }else if(status.equalsIgnoreCase("PAUSED")){
            return "暂停";
        }else{
            return "异常";
        }
    }
}

3,提供对应的Controller


import com.innmall.hotelmanager.common.Result;
import com.innmall.hotelmanager.service.quartz.QuartzUtils;
import com.innmall.hotelmanager.service.quartz.ScheduleJob;
import org.quartz.SchedulerException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

/**
 * Created by lyndon on 16/9/13.
 */
@RestController
@RequestMapping(value = {"/v1/job"})
public class QuartzController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    private QuartzUtils quartzUtils;

    //获取定时任务的列表
    @RequestMapping(value = {"/getJobList"})
    public Result getPlanJobList(String openId){
        //QuartzUtils quartzUtils = new QuartzUtils();
        List<ScheduleJob> list = null;
        try {
            list = quartzUtils.getPlanJobList();
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
        return Result.success(list);
    }

    //暂停任务
    @RequestMapping(value = {"/pauseJob"})
    public Result pauseJob(String openId){
        //QuartzUtils quartzUtils = new QuartzUtils();
        ScheduleJob job = new ScheduleJob();
        job.setJobGroup("innmall_job");
        job.setJobName("refreshWxToKenJobDetail");
        try {
            quartzUtils.pauseJob(job);
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
        return Result.success("暂停成功");
    }

    //恢复任务
    @RequestMapping(value = {"/resumeJob"})
    public Result resumeJob(String openId){
        //QuartzUtils quartzUtils = new QuartzUtils();
        ScheduleJob job = new ScheduleJob();
        job.setJobGroup("innmall_job");
        job.setJobName("refreshWxToKenJobDetail");
        try {
            quartzUtils.resumeJob(job);
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
        return Result.success("恢复成功");
    }

    //立即触发任务
    @RequestMapping(value = {"/triggerJob"})
    public Result triggerJob(String openId){
        //QuartzUtils quartzUtils = new QuartzUtils();
        ScheduleJob job = new ScheduleJob();
        job.setJobGroup("innmall_job");
        job.setJobName("refreshWxToKenJobDetail");
        try {
            quartzUtils.triggerJob(job);
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
        return Result.success("触发成功");
    }

    //删除任务
    @RequestMapping(value = {"/deleteJob"})
    public Result deleteJob(String openId){
        //QuartzUtils quartzUtils = new QuartzUtils();
        ScheduleJob job = new ScheduleJob();
        job.setJobGroup("innmall_job");
        job.setJobName("refreshWxToKenJobDetail");
        try {
            quartzUtils.deleteJob(job);
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
        return Result.success("触发成功");
    }
  
}

4,接下来,我们就可以进行单元测试了。

5,需要注意的地方:

5.1 service层:

@Resource
private Scheduler scheduler;

这里是因为我们在xml里面已经配置对应的工厂bean,所以可以在这里可以直接注入:

<bean id="quartzScheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean"     
 destroy-method="destroy">

5.2 关于区分不同业务的触发器和任务,可以配置job和trigger的group属性,这样我们便以区分,如果不设置,quartz将使用default关键字:

   <bean id="refreshWxToKenJobDetail"
          class="org.springframework.scheduling.quartz.JobDetailFactoryBean">
        <property name="jobClass" value="com.innmall.hotelmanager.timer.RefreshWxToKen"/>
        <property name="durability" value="true" />
        <property name="requestsRecovery" value="true" />
        <property name="group" value="innmall_job"/>
    </bean>
    <bean id="refreshWxToKenTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
        <property name="jobDetail" ref="refreshWxToKenJobDetail"/>
        <!-- 每10s钟运行一次 -->
        <property name="cronExpression" value="0/10 * * * * ?"/>
        <property name="misfireInstruction" value="2"/>
        <property name="group" value="innmall_trigger"/>
    </bean>

5.3 关于定时任务恢复后,我们如果不需要让之前错过的定时任务再执行一次,可以设置misfireInstruction的属性,其实就是

CronTrigger.MISFIRE_INSTRUCTION_DO_NOTHING

进去可以看见对应的值为2.
并且需要在我们恢复任务的时候调用更新的方法,可以见上文的QuartzUtil中的方法。

//重置当前时间
this.rescheduleJob(scheduleJob);

5.4 如果需要定时任务恢复后,需要将之前错过的执行一次,那么只需要在xml里面去除misfireInstruction属性,其实就是使用默认配置,并且在恢复的时候不调用更新的方法。

关于quartz的使用方法,暂时就介绍到这里,如果有什么地方有问题,欢迎指正,后面将持续研究对应的异常处理机制,敬请关注~

上一篇下一篇

猜你喜欢

热点阅读