| | |
| | | |
| | | import com.ruoyi.inspectiontask.pojo.TimingTask; |
| | | import lombok.RequiredArgsConstructor; |
| | | import lombok.extern.slf4j.Slf4j; |
| | | import org.quartz.*; |
| | | import org.springframework.stereotype.Service; |
| | | |
| | |
| | | import java.util.stream.Collectors; |
| | | |
| | | @Service |
| | | @Slf4j |
| | | @RequiredArgsConstructor |
| | | public class TimingTaskScheduler { |
| | | |
| | |
| | | // 获取现有触发器并转换为 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,确保持久化配置 |
| | |
| | | .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(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()); |
| | | } |
| | | |
| | | /** |
| | | * 暂停任务 |
| | | */ |
| | | public void pauseTimingTask(Long taskId) throws SchedulerException { |