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
package com.ruoyi.device.init;
 
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.device.mapper.MaintenanceTaskMapper;
import com.ruoyi.device.pojo.MaintenanceTask;
import com.ruoyi.device.service.impl.MaintenanceTaskScheduler;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
 
import java.util.List;
 
/**
 * 启动时把已启用的保养定时任务注册到调度器,保证历史数据(直接写库、从未经过 service)也能被执行
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class MaintenanceTaskRegistrar implements ApplicationRunner {
 
    private final MaintenanceTaskMapper maintenanceTaskMapper;
    private final MaintenanceTaskScheduler maintenanceTaskScheduler;
 
    @Override
    public void run(ApplicationArguments args) {
        try {
            List<MaintenanceTask> tasks = maintenanceTaskMapper.selectList(
                    new QueryWrapper<MaintenanceTask>().eq("deleted", 0).eq("is_active", 1));
            int registered = 0;
            for (MaintenanceTask task : tasks) {
                try {
                    if (maintenanceTaskScheduler.isRegistered(task.getId())) {
                        continue;
                    }
                    maintenanceTaskScheduler.scheduleMaintenanceTask(task);
                    registered++;
                } catch (Exception e) {
                    log.warn("保养定时任务注册失败 id={} name={}", task.getId(), task.getTaskName(), e);
                }
            }
            log.info("保养定时任务注册完成:待注册 {} 条,本次新注册 {} 条", tasks.size(), registered);
        } catch (Exception e) {
            log.error("保养定时任务启动注册失败", e);
        }
    }
}