Quartz 持久化到MySQL 并创建触发器

示例:

    pom.xml

  
        
            org.springframework.boot
            spring-boot-starter-quartz
        

   实现步骤:

    1. 


import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.example.config.ConfigurationJSON;
import org.example.config.quartz.DelQuartzJob;
import org.example.utils.QuartzCronDateUtils;
import org.example.config.quartz.AddQuartzJob;
import org.example.model.common.CommonResult;
import org.example.model.common.JsonTMSBean;
import org.example.model.entity.PersonnelAccessAuthority;
import org.example.service.PersonnelReceivingService;
import org.example.service.QuartzService;
import org.example.utils.HttpClientUtils;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author 
 * @version 1.0
 * @PACKAGE_NAME: org.example.service.impl
 * @date 2021/11/29 14:41 周一
 */
@Slf4j
@Service
public class PersonnelReceivingServiceImpl  implements PersonnelReceivingService {

    
     @Autowired
     QuartzService quartzService;
     @Autowired
      Scheduler  scheduler;

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    Map map = new HashMap(2);

    @Override
    public String  receiveLeaveCancellation( ) {
             try {
                 String personCode1 ="4131231123";
                    String startTime = "2022-05-26 12:40:00";
                    String endTime ="2022-06-27 11:40:00";
                    //有效期开始时间
                    Date parse = sdf.parse(startTime);
                    long starTime = parse.getTime();
                    Calendar calendar= Calendar.getInstance();
                    Date time = calendar.getTime();
                    long newstarTime = time.getTime();
                    //有效期截止时间
                    Date endPresonTime = sdf.parse(endTime);
                    long endTimelong = endPresonTime.getTime();
                    Calendar calendarendTime= Calendar.getInstance();
                    Date timeendTime = calendarendTime.getTime();
                    long newendTimee = timeendTime.getTime();
                    //判断如果开始时间小于当前时间,就抛弃
                    if(starTime<=newstarTime&&endTimelong<=newendTimee){
                        log.error("判断如果开始和结束时间小于当前时间:"+JSONUtil.toJsonStr(personCode1));
                    }else {
                        Date startDate = new Date(starTime);
                        String startcron = QuartzCronDateUtils.getCron(startDate);
                        JobKey jobKey = JobKey.jobKey("addJob", "addGroup");
                        JobDetail jobDetail1 = scheduler.getJobDetail(jobKey);
                        if (jobDetail1 == null) {
                            quartzService.addJob(AddQuartzJob.class, "addJob", personCode1, startcron, personCode1);
                        } else {
                            // 获取触发器标识  如果有的话 更新时间就可以了
                            TriggerKey triggerKeys = TriggerKey.triggerKey(personCode1, "addGroup");
                            CronTrigger triggers = (CronTrigger) scheduler.getTrigger(triggerKeys);
                            if(triggers!=null){
                                // 表达式调度构建器
                                CronScheduleBuilder scheduleBuilder = CronScheduleBuilder
                                        .cronSchedule(startcron);
                                // Trigger已存在,更新相应的定时设置
                                // 按新的cronExpression表达式重新构建trigger
                                triggers = triggers.getTriggerBuilder()
                                        .forJob(JobKey.jobKey("addJob","addGroup"))
                                        .withIdentity(triggerKeys)
                                        .withSchedule(scheduleBuilder).build();
                                // 按新的trigger重新设置job执行
                                scheduler.rescheduleJob(triggerKeys, triggers);
                            }else {
                                quartzService.addTrigger(jobDetail1, personCode1, startcron);

                            }
                        }
                        //执行结束时间
                        Date endDate = new Date(endTimelong);
                        String endCron = QuartzCronDateUtils.getCron(endDate);
                        JobKey updatejobKey = JobKey.jobKey("updateJob", "updateGroup");
                        JobDetail jobDetailUpdate = scheduler.getJobDetail(updatejobKey);
                        if (jobDetailUpdate == null) {
                            quartzService.delJob(DelQuartzJob.class, "updateJob", "updateGroup", personCode1, endCron, personCode1);
                        } else {
                            // 获取触发器标识  如果有的话 更新时间就可以了
                            TriggerKey triggerKeys = TriggerKey.triggerKey(personCode1, "updateGroup");
                            CronTrigger triggers = (CronTrigger) scheduler.getTrigger(triggerKeys);
                            if(triggers!=null){
                                // 表达式调度构建器
                                CronScheduleBuilder scheduleBuilder = CronScheduleBuilder
                                        .cronSchedule(endCron);
                                // Trigger已存在,更新相应的定时设置
                                // 按新的cronExpression表达式重新构建trigger
                                triggers = triggers.getTriggerBuilder()
                                        .forJob(JobKey.jobKey("addJob","addGroup"))
                                        .withIdentity(triggerKeys)
                                        .withSchedule(scheduleBuilder).build();
                                // 按新的trigger重新设置job执行
                                scheduler.rescheduleJob(triggerKeys, triggers);
                            }else {
                                quartzService.delTrigger(jobDetailUpdate, personCode1, "updateGroup", endCron, personCode1);
                            }

                        }
                    }

        }catch (Exception ex){
              log.error(personnelAccessAuthority +"人员信息数据转换失败:"+ex.getMessage());
        }
        return  null
    }

}
package org.example.service;

import org.example.config.quartz.AddQuartzJob;
import org.example.config.quartz.DelQuartzJob;
import org.quartz.JobDetail;

import java.util.Map;

/**
 * @author 
 * @version 1.0
 * @PACKAGE_NAME: org.example.service
 * @date 2021/12/8 14:53 周三
 */
public interface QuartzService {


    /**
     * 增加一个job
     * @param jobClass
     * 任务实现类
     * @param jobName
     *  任务名称(建议唯一)
     * @param jobGroupName
     *   任务组名
     * @param triggerName
     *   触发器名
     * @param jobTime
     *  时间表达式 (如:0/5 * * * * ? )
     * @param personCode
     * @return
     */
    void addJob(Class jobClass, String jobName, String jobGroupName, String triggerName, String jobTime, String personCode);

    void addTrigger(JobDetail jobDetail, String personCodeTime, String jobGroupName, String cron, String personCode);

    void delJob(Class delQuartzJobClass, String updateJob, String updateGroup, String personCodeEndTime, String endCron, String personCode);

    void delTrigger(JobDetail jobDetailUpdate, String personCodeEndTime, String updateGroup, String endCron, String personCode);

    /**
     * 任务
     * @param delVisitorQuartzJobClass
     * @param visitorAddJob
     * @param visitorAddGroup
     * @param visitorStarttime
     * @param endCron
     * @param visitorData
     */
    void addVisitorJob(Class delVisitorQuartzJobClass, String visitorAddJob, String visitorAddGroup, String visitorStarttime, String endCron, VisitorData visitorData);

    /**
     * 添加触发器
     * @param jobDetail
     * @param visitorStarttime
     * @param visitorAddGroup
     * @param endCron
     * @param visitorData
     */
    void visitorTrigger(JobDetail jobDetail, String visitorStarttime, String visitorAddGroup, String endCron, VisitorData visitorData);

    void delVisitorJob(Class delVisitorQuartzJobClass, String updateVisitorJob, String updateVisitorGroup, String personCodeEndTime, String endCronVisitor, VisitorData visitorData);

}
package org.example.service.impl;


import lombok.extern.slf4j.Slf4j;
import org.example.config.quartz.AddQuartzJob;
import org.example.config.quartz.DelQuartzJob;
import org.example.service.QuartzService;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

import static org.quartz.CronScheduleBuilder.cronSchedule;
import static org.quartz.TriggerBuilder.newTrigger;

/**
 * quartz逻辑
 * @author gourd
 */
@Slf4j
@Service
public class QuartzServiceImpl implements QuartzService {

    @Autowired
    private Scheduler scheduler;

    @PostConstruct
    public void startScheduler() {
        try {
            scheduler.start();
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }

    /**
     * 添加出入权限任务
     *  @param jobClass
     *            任务实现类
     * @param jobName
     *            任务名称(建议唯一)
     * @param jobGroupName
 *            任务组名
     *            TriggerName  触发器名称
     * @param jobTime
*            时间表达式
     *
     * @param personCode
     */
    @Override
    public void addJob(Class jobClass,
                            String jobName,
                            String jobGroupName,
                            String triggerName,
                            String jobTime,
                            String personCode) {
        try {
            // 创建jobDetail实例,绑定Job实现类
            // 指明job的名称,所在组的名称,以及绑定job类
            // 任务名称和组构成任务key
            JobDetail  jobDetail = JobBuilder.newJob(jobClass).withIdentity(jobName, jobGroupName)
                    .build();
            // 设置job参数jobName
            if(StringUtils.isNotBlank(personCode)){
                jobDetail.getJobDataMap().put("personCode",personCode);
            }
            // 定义调度触发规则
            // 使用cornTrigger规则
            // 触发器key
            Trigger trigger = newTrigger().withIdentity(triggerName, jobGroupName)

                    .startAt(DateBuilder.futureDate(1, DateBuilder.IntervalUnit.SECOND))
                    .withSchedule(cronSchedule(jobTime)).build();
              trigger.getJobDataMap().put("personCode",personCode);
            // 把作业和触发器注册到任务调度中
            scheduler.scheduleJob(jobDetail, trigger);
        } catch (Exception e) {
            log.error("添加出入权限任务失败:"+e.getMessage());
        }
    }

    /**
     * 添加出入权限触发器
     * @param jobDetail1
     * @param personCodeTime
     * @param jobGroupName
     * @param cron
     * @param jobData
     */
    @Override
    public void addTrigger(JobDetail jobDetail1, String personCodeTime, String jobGroupName, String cron, String jobData) {
        try {
            // 定义调度触发规则
            // 把作业和触发器注册到任务调度中
            scheduler.scheduleJob(newTrigger().withIdentity(new TriggerKey(personCodeTime, jobGroupName)).withSchedule(
                    cronSchedule(cron)).forJob(jobDetail1).usingJobData("personCode",jobData).build());
        } catch (Exception e) {
            log.error("添加出入权限触发器失败:"+e.getMessage());
        }
    }

    /**
     * 新增修改权限job
     * @param jobClass
     * @param jobName
     * @param jobGroupName
     * @param triggerName
     * @param jobTime
     * @param jobData
     */
    @Override
    public void delJob(Class jobClass,
                       String jobName,
                       String jobGroupName,
                       String triggerName,
                       String jobTime,
                       String jobData) {
        try {
            // 创建jobDetail实例,绑定Job实现类
            // 指明job的名称,所在组的名称,以及绑定job类
            // 任务名称和组构成任务key
            JobDetail  jobDetail = JobBuilder.newJob(jobClass).withIdentity(jobName, jobGroupName)
                    .build();
            // 设置job参数jobName
            if(jobData!= null){
                jobDetail.getJobDataMap().put("personCode",jobData);
            }
            // 定义调度触发规则
            // 使用cornTrigger规则
            // 触发器key
            Trigger trigger = newTrigger().withIdentity(triggerName, jobGroupName)
                    .startAt(DateBuilder.futureDate(1, DateBuilder.IntervalUnit.SECOND))
                    .withSchedule(cronSchedule(jobTime)).build();
            trigger.getJobDataMap().put("personCode",jobData);

            // 把作业和触发器注册到任务调度中
            scheduler.scheduleJob(jobDetail, trigger);
        } catch (Exception e) {
            log.error("修改出入任务失败:"+e.getMessage());
        }
    }

    /**
     * 添加修改出入权限触发器
     * @param jobDetail
     * @param personCodeEndTime
     * @param updateGroup
     * @param endCron
     * @param jobData
     */
    @Override
    public void delTrigger(JobDetail jobDetail, String personCodeEndTime, String updateGroup, String endCron, String jobData) {
        try {
            // 定义调度触发规则
            // 把作业和触发器注册到任务调度中
            scheduler.scheduleJob(newTrigger().withIdentity(new TriggerKey(personCodeEndTime, updateGroup)).withSchedule(
                            cronSchedule(endCron)).forJob(jobDetail).usingJobData("personCode",jobData).build());
        } catch (Exception e) {
            log.error("添加修改出入权限触发器失败:" + e.getMessage());
        }
       }

    /**
     * 任务信息
     * @param jobClass
     * @param jobName
     * @param jobGroupName
     * @param triggerName
     * @param jobTime
     * @param visitorData
     */
    @Override
    public void addVisitorJob(Class jobClass,
                              String jobName,
                              String jobGroupName,
                              String triggerName,
                              String jobTime,
                              VisitorData visitorData) {

        try {
            // 创建jobDetail实例,绑定Job实现类
            // 指明job的名称,所在组的名称,以及绑定job类
            // 任务名称和组构成任务key
            JobDetail  jobDetail = JobBuilder.newJob(jobClass).withIdentity(jobName, jobGroupName)
                    .build();
            // 定义调度触发规则
            // 使用cornTrigger规则
            String visitor = JSONObject.toJSONString(visitorData);
            // 触发器key
            Trigger trigger = newTrigger().withIdentity(triggerName, jobGroupName)

                    .startAt(DateBuilder.futureDate(1, DateBuilder.IntervalUnit.SECOND))
                    .withSchedule(cronSchedule(jobTime)).build();
            trigger.getJobDataMap().put("visitorData",visitor);
            // 把作业和触发器注册到任务调度中
            scheduler.scheduleJob(jobDetail, trigger);
        } catch (Exception e) {
            log.error("添加访客出入权限任务失败:"+e.getMessage());
        }

    }

    /**
     * 出入触发器
     * @param jobDetail
     * @param visitorStarttime
     * @param visitorAddGroup
     * @param endCron
     * @param visitorData
     */
    @Override
    public void visitorTrigger(JobDetail jobDetail,
                                  String visitorStarttime,
                                  String visitorAddGroup,
                                  String endCron,
                                  VisitorData visitorData) {
        try {
            // 定义调度触发规则
            String visitor = JSONObject.toJSONString(visitorData);
            // 把作业和触发器注册到任务调度中
            scheduler.scheduleJob(newTrigger().withIdentity(new TriggerKey(visitorStarttime, visitorAddGroup)).withSchedule(
                    cronSchedule(endCron)).forJob(jobDetail).usingJobData("visitorData", visitor).build());
        } catch (Exception e) {
            log.error("出入权限触发器失败:" + e.getMessage());
        }
    }

    /**
     * 删除出入权限
     * @param jobClass
     * @param jobName
     * @param jobGroupName
     * @param triggerName
     * @param jobTime
     * @param visitorData
     */
    @Override
    public void delVisitorJob(Class jobClass,
                              String jobName,
                              String jobGroupName,
                              String triggerName,
                              String jobTime,
                              VisitorData visitorData) {

        try {
            // 创建jobDetail实例,绑定Job实现类
            // 指明job的名称,所在组的名称,以及绑定job类
            // 任务名称和组构成任务key
            JobDetail  jobDetail = JobBuilder.newJob(jobClass).withIdentity(jobName, jobGroupName)
                    .build();
            // 定义调度触发规则
            // 使用cornTrigger规则
            String visitor = JSONObject.toJSONString(visitorData);
            // 触发器key
            Trigger trigger = newTrigger().withIdentity(triggerName, jobGroupName)

                    .startAt(DateBuilder.futureDate(1, DateBuilder.IntervalUnit.SECOND))
                    .withSchedule(cronSchedule(jobTime)).build();
            trigger.getJobDataMap().put("visitorData",visitor);
            // 把作业和触发器注册到任务调度中
            scheduler.scheduleJob(jobDetail, trigger);
        } catch (Exception e) {
            log.error("删除出入权限任务失败:"+e.getMessage());
        }

    }

package org.example.config.quartz;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.example.config.ConfigurationJSON;
import org.example.model.common.DataModel;
import org.example.model.common.JsonTMSBean;
import org.example.model.common.TmsLeaveCancelPerson;
import org.example.utils.HttpClientUtils;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

/**
 * 业务处理
 * @author gourd
 */
@Component
public class AddQuartzJob extends QuartzJobBean {


    @Override
    protected void executeInternal(JobExecutionContext arg0)  {
            JsonTMSBean jsonTMSBean=null;
            //人员权限信息
            TmsLeaveCancelPerson tmsLeaveCancelPerson =null;
            // 获取参数
            JobDataMap jobDatQuartzCronDateUtilsaMap = arg0.getJobDetail().getJobDataMap();
            System.out.println(new Date() +"     新增执行的业务====="+JSON.toJSONString(jobDatQuartzCronDateUtilsaMap));
              // 获取参数
            JobDataMap jobDataMap = context.getTrigger().getJobDataMap();
            // 业务逻辑
            String visitorData = jobDataMap.getString("visitorData");


    }

}
package org.example.utils;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author 
 * @version 1.0
 * @PACKAGE_NAME: org.example.config.quartz
 * @date 2021/12/8 14:52 周三
 */

public class QuartzCronDateUtils {
    /***
     *  日期转换cron表达式时间格式
     * @param date
     * @param dateFormat
     * @return
     */
    public static String formatDateByPattern(Date date,String dateFormat){
        SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
        String formatTimeStr = null;
        if (date != null) {
            formatTimeStr = sdf.format(date);
        }
        return formatTimeStr;
    }
    /***
     * convert Date to cron
     * @param date:时间
     * @return
     */
    public static String getCron(Date  date){
        String dateFormat="ss mm HH dd MM ? yyyy";
        return formatDateByPattern(date,dateFormat);
    }
}

你可能感兴趣的:(java,mysql,数据库,database)