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
package cn.iocoder.yudao.module.mes.job.collect;
 
import cn.iocoder.yudao.module.mes.dal.mysql.collect.MesCollectMessageMapper;
import cn.iocoder.yudao.module.mes.dal.mysql.collect.MesCollectRealtimeHistoryMapper;
import cn.iocoder.yudao.module.mes.framework.collect.config.MesCollectProperties;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
 
import java.time.LocalDateTime;
 
/**
 * MES 数采历史数据清理任务
 *
 * <p>原始报文保留 7 天,实时历史保留 30 天,每日 03:30 执行。</p>
 *
 * @author 超级管理员
 */
@Component
@Slf4j
public class MesCollectCleanupJob {
 
    @Resource
    private MesCollectProperties properties;
    @Resource
    private MesCollectMessageMapper messageMapper;
    @Resource
    private MesCollectRealtimeHistoryMapper realtimeHistoryMapper;
 
    @Scheduled(cron = "0 30 3 * * ?")
    public void execute() {
        MesCollectProperties.Retention retention = properties.getRetention();
        int batchSize = retention.getBatchSize() == null || retention.getBatchSize() <= 0
                ? 50000 : retention.getBatchSize();
        int rawDeleted = deleteInBatches(() -> messageMapper.deleteBefore(
                LocalDateTime.now().minusDays(retention.getRawDays()), batchSize), batchSize);
        int realtimeDeleted = deleteInBatches(() -> realtimeHistoryMapper.deleteBefore(
                LocalDateTime.now().minusDays(retention.getRealtimeDays()), batchSize), batchSize);
        log.info("[execute][数采历史清理完成:原始报文 {} 条,实时历史 {} 条]", rawDeleted, realtimeDeleted);
    }
 
    private int deleteInBatches(DeleteAction action, int batchSize) {
        int total = 0;
        int deleted;
        do {
            deleted = action.delete();
            total += deleted;
        } while (deleted >= batchSize);
        return total;
    }
 
    @FunctionalInterface
    private interface DeleteAction {
        int delete();
    }
 
}