| | |
| | | package com.ruoyi.device.service.impl; |
| | | |
| | | import com.ruoyi.device.pojo.MaintenanceTask; |
| | | 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; |
| | |
| | | */ |
| | | @Service |
| | | @Slf4j |
| | | @RequiredArgsConstructor |
| | | public class MaintenanceTaskScheduler { |
| | | |
| | | @Autowired |
| | | private Scheduler scheduler; |
| | | private final Scheduler scheduler; |
| | | |
| | | /** |
| | | * 添加新任务到调度器 |
| | |
| | | // 获取现有触发器并转换为 CronTrigger |
| | | Trigger oldTrigger = scheduler.getTrigger(triggerKey); |
| | | if (!(oldTrigger instanceof CronTrigger)) { |
| | | throw new SchedulerException("Existing trigger is not a CronTrigger"); |
| | | // 触发器不存在(首次部署后从未注册,或调度记录被清理),改为重新创建 |
| | | JobKey jobKey = new JobKey("MaintenanceTask_" + task.getId()); |
| | | if (scheduler.checkExists(jobKey)) { |
| | | scheduler.deleteJob(jobKey); |
| | | } |
| | | scheduleMaintenanceTask(task); |
| | | return; |
| | | } |
| | | |
| | | // 3. 构建CronTrigger,确保持久化配置 |
| | |
| | | .withDescription(task.getTaskName() + "_TRIGGER") // 触发器描述 |
| | | .forJob(oldTrigger.getJobKey()) // 关联对应的Job |
| | | .withSchedule(CronScheduleBuilder |
| | | .cronSchedule(convertToCronExpression(task)) // 错过执行时的策略(根据业务调整) |
| | | .cronSchedule(convertToCronExpression(task)) |
| | | .withMisfireHandlingInstructionDoNothing() |
| | | ) |
| | | // 4. 设置开始时间(若为null则立即生效) |
| | | .startAt(task.getNextExecutionTime() != null |
| | |
| | | } |
| | | |
| | | /** |
| | | * 确保任务已在调度器中,未注册时补注册(应用启动时恢复使用) |
| | | */ |
| | | public void ensureScheduled(MaintenanceTask task){ |
| | | try { |
| | | JobKey jobKey = new JobKey("MaintenanceTask_" + task.getId()); |
| | | if (scheduler.checkExists(jobKey)) { |
| | | return; |
| | | } |
| | | scheduleMaintenanceTask(task); |
| | | log.info("补注册保养定时任务: id={}, name={}", task.getId(), task.getTaskName()); |
| | | } catch (SchedulerException e) { |
| | | log.error("SchedulerException ensureScheduled ERROR", e); |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * 暂停任务 |
| | | */ |
| | | public void pauseMaintenanceTask(Long taskId) throws SchedulerException { |