spring quartz 实现重启后加载重新加载任务

pom依赖


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

job管理类

package com.seezoon.admin.framework.quartz;


import com.seezoon.framework.utils.CalendarUtils;
import org.apache.commons.lang3.StringUtils;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;

/**
 * @Classname QuartzManager
 * @Description
 * @Date 2023/9/25 9:30
 * @Created by jyl
 */

@Service
public class QuartzManager {

    // 任务调度
    @Autowired
    private Scheduler scheduler;

    /**
     * 开始执行任务
     *
     * @throws SchedulerException
     */
    public void startJob(String jobName, String jobGroup, String cron) throws Exception {
        //查到信息进行修改操作  查不到进行新增操作
        String jobInfo = getJobInfo(jobName, jobGroup);
        System.out.println("触发定时任务 jobName :" + jobName + ", jobGroup :" +jobGroup);
        if (StringUtils.isBlank(jobInfo)) {
            //startJob(scheduler, jobName, jobGroup, formatDateByPattern(CalendarUtils.format(cron, CalendarUtils.DATETIME_FORMAT)));
            startJob(scheduler, jobName, jobGroup, cron);
        } else {
            modifyJob(jobName, jobGroup, cron);
        }
    }

    /**
     * 获取Job信息
     */
    public String getJobInfo(String name, String group) throws Exception {
        TriggerKey triggerKey = new TriggerKey(name, group);
        CronTrigger cronTrigger = (CronTrigger) scheduler.getTrigger(triggerKey);
        if (null == cronTrigger) {
            return null;
        }
        return String.format("time:%s,state:%s", cronTrigger.getCronExpression(),
                scheduler.getTriggerState(triggerKey).name());

    }

    /**
     * 修改某个任务的执行时间
     */
    public boolean modifyJob(String name, String group, String time) throws SchedulerException {
        //String newTime = formatDateByPattern(CalendarUtils.format(time, CalendarUtils.DATETIME_FORMAT));
        Date date = null;
        TriggerKey triggerKey = new TriggerKey(name, group);
        CronTrigger cronTrigger = (CronTrigger) scheduler.getTrigger(triggerKey);
        String oldTime = cronTrigger.getCronExpression();
        if (!oldTime.equalsIgnoreCase(time)) {
            CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(time);
            CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(name, group)
                    .withSchedule(cronScheduleBuilder).build();
            date = scheduler.rescheduleJob(triggerKey, trigger);
        }
        return date != null;
    }


    /**
     * 删除某个任务
     */
    public void deleteJob(String name, String group) throws SchedulerException {
        JobKey jobKey = new JobKey(name, group);
        JobDetail jobDetail = scheduler.getJobDetail(jobKey);
        if (jobDetail == null)
            return;
        scheduler.deleteJob(jobKey);
    }

    private void startJob(Scheduler scheduler, String jobName, String jobGroup, String cron) throws SchedulerException {

        JobDetail jobDetail = JobBuilder.newJob(SchedulerQuartzJob.class).withIdentity(jobName, jobGroup).build();
        CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(cron);
        CronTrigger cronTrigger = TriggerBuilder.newTrigger().withIdentity(jobName, jobGroup)
                .withSchedule(cronScheduleBuilder).build();
        scheduler.scheduleJob(jobDetail, cronTrigger);
    }


    /**
     * 暂停某个任务
     */
    public void pauseJob(String jobName, String group) throws SchedulerException {
        JobKey jobKey = JobKey.jobKey(jobName, group);

        JobDetail jobDetail = scheduler.getJobDetail(jobKey);
        if (jobDetail == null) return;
        scheduler.pauseJob(jobKey);


    }


    private static final SimpleDateFormat sdf = new SimpleDateFormat("ss mm HH dd MM ?");

    /***
     * 日期转换cron表达式
     */
    public static String formatDateByPattern(Date date) {
        String formatTimeStr = null;
        if (Objects.nonNull(date)) {
            formatTimeStr = sdf.format(date);
        }
        return formatTimeStr;
    }


}

SchedulerQuartzJob具体job执行调用

package com.seezoon.admin.framework.quartz;

import cn.hutool.json.JSONUtil;
import com.lark.oapi.Client;
import com.lark.oapi.core.request.RequestOptions;
import com.lark.oapi.core.utils.Jsons;
import com.lark.oapi.service.im.v1.model.CreateMessageReq;
import com.lark.oapi.service.im.v1.model.CreateMessageReqBody;
import com.lark.oapi.service.im.v1.model.CreateMessageResp;
import com.seezoon.dao.modules.sys.bytedance.OcAdGroupDao;
import com.seezoon.dao.modules.sys.bytedance.OcAlarmConfigDao;
import com.seezoon.dao.modules.sys.bytedance.entity.OcAdGroup;
import com.seezoon.dao.modules.sys.bytedance.entity.OcAlarmConfig;
import com.seezoon.dao.modules.sys.bytedance.entity.OcAlarmConfigCondition;
import com.seezoon.framework.utils.CalendarUtils;
import com.seezoon.framework.utils.JsonToSqlUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @Classname SchedulerQuartzJob
 * @Description
 * @Date 2023/9/25 9:45
 * @Created by jyl
 */
@Slf4j
public class SchedulerQuartzJob implements Job {

    @Autowired
    private OcAlarmConfigDao alarmConfigDao;

    @Autowired
    private OcAdGroupDao ocAdGroupDao;


    @Override
    public void execute(JobExecutionContext arg) throws JobExecutionException {
        log.info("触发定时任务: " + CalendarUtils.getCurrentDate());
        if (null == arg.getTrigger()) return;
        TriggerKey trigger = arg.getTrigger().getKey();


        if (null == trigger) return;
        String guid = trigger.getName();
        String title = trigger.getGroup();

        //业务逻辑
    }





}

LoadTask配置项目启动加载

package com.seezoon.admin.framework.quartz;

import com.seezoon.admin.modules.sys.service.bytedance.OcAlarmConfigService;
import com.seezoon.dao.modules.sys.bytedance.entity.OcAlarmConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

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

/**
 * @Classname LoadTask
 * @Description
 * @Date 2023/9/25 10:30
 * @Created by jyl
 */

@Slf4j
@Component
public class LoadTask {

    @Autowired
    private QuartzManager quartzManager;

    @Autowired
    private OcAlarmConfigService ocAlarmConfigService;


    /**
     * @Description 启动项目时加载所有未执行的任务
     **/
    @PostConstruct
    public void initSchedule() {

        try {
            //从表里获取有效的cron 并启动
            List validAlarmConfig = ocAlarmConfigService.getValidAlarmConfig();
            for (OcAlarmConfig config : validAlarmConfig) {
                if (StringUtils.isBlank(config.getCron())) continue;
                quartzManager.startJob(config.getGuid(), config.getTitle(), config.getCron());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}

你可能感兴趣的:(spring,java,前端)