对比新文件 |
| | |
| | | package com.mzl.flower.schedule; |
| | | |
| | | import com.mzl.flower.entity.film.AiContentTaskConfig; |
| | | import com.mzl.flower.service.film.AiContentTaskConfigService; |
| | | import org.springframework.beans.factory.annotation.Autowired; |
| | | import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler; |
| | | import org.springframework.scheduling.support.CronTrigger; |
| | | import org.springframework.stereotype.Component; |
| | | |
| | | import javax.annotation.PostConstruct; |
| | | import java.util.*; |
| | | import java.util.concurrent.ConcurrentHashMap; |
| | | import java.util.concurrent.ScheduledFuture; |
| | | import java.util.stream.Collectors; |
| | | |
| | | @Component |
| | | public class DynamicTaskManager { |
| | | private final Map<Long, ScheduledFuture<?>> scheduledTasks = new ConcurrentHashMap<>(); |
| | | |
| | | @Autowired |
| | | private ThreadPoolTaskScheduler taskScheduler; |
| | | @Autowired |
| | | private AiContentTaskConfigService configService; |
| | | @Autowired |
| | | private TaskExecutor taskExecutor; |
| | | |
| | | @PostConstruct |
| | | public void init() { |
| | | refreshTasks(); |
| | | } |
| | | |
| | | public synchronized void refreshTasks() { |
| | | List<AiContentTaskConfig> latestConfigs = configService.getEnabledConfigs(); |
| | | Set<Long> latestIds = latestConfigs.stream() |
| | | .map(AiContentTaskConfig::getId) |
| | | .collect(Collectors.toSet()); |
| | | |
| | | // 移除无效任务 |
| | | new HashSet<>(scheduledTasks.keySet()).forEach(id -> { |
| | | if (!latestIds.contains(id)) { |
| | | cancelAndRemoveTask(id); |
| | | } |
| | | }); |
| | | |
| | | // 更新/新增任务 |
| | | latestConfigs.forEach(config -> { |
| | | ScheduledFuture<?> existingTask = scheduledTasks.get(config.getId()); |
| | | |
| | | if (existingTask == null) { |
| | | registerNewTask(config); |
| | | } else if (isConfigModified(config)) { |
| | | cancelAndRemoveTask(config.getId()); |
| | | registerNewTask(config); |
| | | } |
| | | }); |
| | | } |
| | | |
| | | private void registerNewTask(AiContentTaskConfig config) { |
| | | ScheduledFuture<?> future = taskScheduler.schedule( |
| | | () -> taskExecutor.executeTask(config), |
| | | new CronTrigger(config.getCron()) |
| | | ); |
| | | scheduledTasks.put(config.getId(), future); |
| | | } |
| | | |
| | | private void cancelAndRemoveTask(Long taskId) { |
| | | ScheduledFuture<?> task = scheduledTasks.get(taskId); |
| | | if (task != null) { |
| | | task.cancel(false); // 不中断正在执行的任务 |
| | | scheduledTasks.remove(taskId); |
| | | } |
| | | } |
| | | |
| | | private boolean isConfigModified(AiContentTaskConfig newConfig) { |
| | | // 实现配置变更检查逻辑(比较字段或版本号) |
| | | return true; // 简化示例 |
| | | } |
| | | } |