quatrz定时任务整合模板

1.创建Job

@DisallowConcurrentExecution
@Component
public class SuspendCycleEndJob extends QuartzJobBean {
    @Override
    protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        //获取id
        Trigger trigger = jobExecutionContext.getTrigger();
        JobDataMap jobDataMap =  trigger.getJobDataMap();
        String id = jobDataMap.getString("id");
        SiteStop siteStop = siteStopMapper.get(id);
        //以下是定时实现的业务逻辑
        if (siteStop!=null){
            if(!StringUtils.isEmpty(id)){
                siteStopMapper.updateState(id,"2");
            }
        }
    }
}

通用JobService

@Service
public class CommonJobService {
    @Autowired
    private Scheduler scheduler;
    /**
     * 暂停定时任务
     * @param jName 任务名
     * @param jGroup 任务组
     */
    public void pauseJob(String jName, String jGroup) {
        try {
            scheduler.pauseJob(JobKey.jobKey(jName, jGroup));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 暂停定时触发器
     * @param tName 触发器名
     * @param tGroup 触发器组
     */
    public void pauseTrigger(String tName, String tGroup) {
        try {
            TriggerKey triggerKey = TriggerKey.triggerKey(tName, tGroup);
            scheduler.pauseTrigger(triggerKey); //停止触发器
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 继续定时任务
     * @param jName 任务名
     * @param jGroup 任务组
     */
    public void resumeJob(String jName, String jGroup) {
        try {
            scheduler.resumeJob(JobKey.jobKey(jName, jGroup));
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }
    /**
     * 继续定时触发器
     * @param tName 触发器名
     * @param tGroup 触发器组
     */
    public void resumeTrigger(String tName, String tGroup) {
        try {
            TriggerKey triggerKey = TriggerKey.triggerKey(tName, tGroup);
            scheduler.resumeTrigger(triggerKey);//恢复运行触发器
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 删除定时任务
     * @param jName 任务名
     * @param jGroup 任务组
     */
    public void deleteJob(String jName, String jGroup) {
        try {
            scheduler.deleteJob(JobKey.jobKey(jName, jGroup));
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }
    /**
     * 删除定时触发器
     * @param tName 触发器名
     * @param tGroup 触发器组
     */
    public void deleteTrigger(String tName, String tGroup) {
        try {
            TriggerKey triggerKey = TriggerKey.triggerKey(tName, tGroup);
            scheduler.pauseTrigger(triggerKey); //停止触发器
            scheduler.unscheduleJob(triggerKey);//移除触发器
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

创建触发器

@Service
public class SuspendCycleEndService {
    @Autowired
    private Scheduler scheduler;
    /**
     * 新增一个触发器
     * @param jName 任务名称
     * @param jGroup 任务组
     * @param tName 触发器名称
     * @param tGroup 触发器组
     * @param cron cron表达式
     */
    public void addTrigger(String jName, String jGroup, String tName, String tGroup, String cron,String id) {
        /**
         * StoreDurably
         * 默认情况下,当 Job 没有对应的 Trigger 时,Job 是不能直接被加入调度器中的,或者在 Trigger 过期之后,
         * 当然没有关联 Trigger 的 Job 也会被删除。我们可以通过 JobBuilder 的 StoreDurably 使 Job 独立存储于调度器中。
         *
         */
        try {
            JobKey jobKey = new JobKey(jName, jGroup);
            JobDetail jobDetail = scheduler.getJobDetail(jobKey);
            if(jobDetail == null){
                jobDetail = JobBuilder.newJob(要实现的job.class)
                        .withIdentity(jName, jGroup)
                        .storeDurably()
                        .build();
                Trigger trigger = TriggerBuilder.newTrigger()
                        .withIdentity(tName, tGroup)
                        .usingJobData("id",id) 
                        .startNow()
                        .withSchedule(CronScheduleBuilder.cronSchedule(cron))
                        .build();
                scheduler.start();
                scheduler.scheduleJob(jobDetail, trigger);
            }else{
                Trigger trigger = TriggerBuilder.newTrigger()
                        .withIdentity(tName, tGroup)
                        .usingJobData("id",id)
                        .startNow()
                        .withSchedule(CronScheduleBuilder.cronSchedule(cron))
                        .forJob(jName,jGroup)
                        .build();
                scheduler.scheduleJob(trigger);
                scheduler.start();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

使用定时任务参考

	public void save(SiteStop siteStop) {
        Date now = new Date();
        String state = "";
        if(now.getTime() <= siteStop.getStartTime().getTime()){
            //未开始
            state = "3";
        }else if(now.getTime() >= siteStop.getEndTime().getTime()){
            //已结束
            state = "2";
        }else if(now.getTime() >= siteStop.getStartTime().getTime() && now.getTime() <= siteStop.getEndTime().getTime()){
            //暂停中
            state = "1";
        }
        siteStop.setState(state); //修改状态
        super.save(siteStop);   //保存
        //如果当前时间小于等于开始时间
		if(now.getTime() < siteStop.getStartTime().getTime()) {
			//获取任务执行时间
			Calendar startcal = Calendar.getInstance();
			startcal.setTime(siteStop.getStartTime());
			//获取年月日
			int year = startcal.get(Calendar.YEAR);
			int month = startcal.get(Calendar.MONTH) + 1;   //calendar月是从0-11算的
			int day = startcal.get(Calendar.DATE);
			// 转化cron表达式
			String cron = "";
			cron = "0"+" "+"0"+" "+"0"+" "+day+" "+month+" ? "+year;
			//启动暂停周期任务
			suspendCycleStartService.addTrigger("暂停周期任务","2",siteStop.getId(),"启动暂停周期任务",cron,siteStop.getId());
		}
		//如果当前时间小于结束时间
		if(now.getTime() < siteStop.getEndTime().getTime()) {
			//获取任务执行时间
			Calendar endcal = Calendar.getInstance();
			endcal.setTime(siteStop.getEndTime());
			//获取年月日
			int year = endcal.get(Calendar.YEAR);
			int month = endcal.get(Calendar.MONTH) + 1;
			int day = endcal.get(Calendar.DATE);
			// 转化cron表达式
			String cron = "";
			cron = "0"+" "+"0"+" "+"0"+" "+day+" "+month+" ? "+year;
			//启动暂停周期任务
			suspendCycleEndService.addTrigger("暂停周期任务","2",siteStop.getId(),"结束暂停周期任务",cron,siteStop.getId());
		}
	}

corn表达式封装

public class CronUtil {
    public static String getCron(Date time){
        //获取任务执行时间
        Calendar startcal = Calendar.getInstance();
        startcal.setTime(time);  //time为需要形参 传入使用 生成cron
        //获取年月日
        int year = startcal.get(Calendar.YEAR);
        int month = startcal.get(Calendar.MONTH) + 1;
        int day = startcal.get(Calendar.DATE);
        // 转化cron表达式
        String cron = "";
        // 从右到左 年 月 日 时 分 秒
        cron = "0"+" "+"0"+" "+"0"+" "+day+" "+month+" ? "+year;
        return cron;
    }
}

你可能感兴趣的