cloudroam
4 天以前 46715d892da947c31f07796fdc79dbbef06677b3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package com.mzl.flower.schedule;
 
import com.mzl.flower.entity.film.AiContentTaskConfig;
import com.mzl.flower.mapper.film.AiContentTaskConfigMapper;
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 javax.annotation.Resource;
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;
    @Resource
    private AiContentTaskConfigMapper aiContentTaskConfigMapper;
    @Autowired
    private TaskExecutor taskExecutor;
 
    @PostConstruct
    public void init() {
        refreshTasks();
    }
 
    public synchronized void refreshTasks() {
        List<AiContentTaskConfig> latestConfigs = aiContentTaskConfigMapper.getAiContentTaskConfigAll();
        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; // 简化示例
    }
}