云
2026-10-27 0a4d548b6bf9cfef252400fb6d6612e45cf5b602
src/main/java/com/ruoyi/inspectiontask/service/impl/TimingTaskScheduler.java
@@ -1,8 +1,9 @@
package com.ruoyi.inspectiontask.service.impl;
import com.ruoyi.inspectiontask.pojo.TimingTask;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.LocalTime;
@@ -13,10 +14,11 @@
import java.util.stream.Collectors;
@Service
@Slf4j
@RequiredArgsConstructor
public class TimingTaskScheduler {
    @Autowired
    private Scheduler scheduler;
    private final Scheduler scheduler;
    /**
     * 添加新任务到调度器
@@ -36,7 +38,13 @@
        // 获取现有触发器并转换为 CronTrigger
        Trigger oldTrigger = scheduler.getTrigger(triggerKey);
        if (!(oldTrigger instanceof CronTrigger)) {
            throw new SchedulerException("Existing trigger is not a CronTrigger");
            // 触发器不存在(首次部署后从未注册,或调度记录被清理),改为重新创建
            JobKey jobKey = new JobKey("timingTask_" + task.getId());
            if (scheduler.checkExists(jobKey)) {
                scheduler.deleteJob(jobKey);
            }
            scheduleTimingTask(task);
            return;
        }
        // 3. 构建CronTrigger,确保持久化配置
@@ -45,7 +53,8 @@
                .withDescription(task.getTaskName() + "_TRIGGER") // 触发器描述
                .forJob(oldTrigger.getJobKey())                       // 关联对应的Job
                .withSchedule(CronScheduleBuilder
                        .cronSchedule(convertToCronExpression(task)) // 错过执行时的策略(根据业务调整)
                        .cronSchedule(convertToCronExpression(task))
                        .withMisfireHandlingInstructionDoNothing()
                )
                // 4. 设置开始时间(若为null则立即生效)
                .startAt(task.getNextExecutionTime() != null
@@ -63,6 +72,18 @@
//                .build();
        scheduler.rescheduleJob(triggerKey, newTrigger);
    }
    /**
     * 确保任务已在调度器中,未注册时补注册(应用启动时恢复使用)
     */
    public void ensureScheduled(TimingTask task) throws SchedulerException {
        JobKey jobKey = new JobKey("timingTask_" + task.getId());
        if (scheduler.checkExists(jobKey)) {
            return;
        }
        scheduleTimingTask(task);
        log.info("补注册巡检定时任务: id={}, name={}", task.getId(), task.getTaskName());
    }
    /**
@@ -84,9 +105,13 @@
    /**
     * 删除任务
     */
    public void unscheduleTimingTask(Long taskId) throws SchedulerException {
        JobKey jobKey = new JobKey("timingTask_" + taskId);
        scheduler.deleteJob(jobKey);
    public void unscheduleTimingTask(Long taskId){
        try {
            JobKey jobKey = new JobKey("timingTask_" + taskId);
            scheduler.deleteJob(jobKey);
        }catch (SchedulerException e){
            throw new RuntimeException(e);
        }
    }
    private JobDetail buildJobDetail(TimingTask task) {