wlzboy
2026-03-19 c5ac97682e3b4ca748541ace97cb37a2295bd81e
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
package com.ruoyi.quartz.task;
 
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.ruoyi.system.service.IVehicleGpsService;
 
/**
 * 清理车辆GPS历史数据任务
 */
@Component("cleanVehicleGpsTask")
public class CleanVehicleGpsTask {
    private static final Logger log = LoggerFactory.getLogger(CleanVehicleGpsTask.class);
 
    /** 每批删除数量 */
    private static final int BATCH_SIZE = 10000;
    /** 每批间隔时间(毫秒),避免连续删除对数据库压力过大 */
    private static final long BATCH_INTERVAL_MS = 500;
 
    @Autowired
    private IVehicleGpsService vehicleGpsService;
 
    /**
     * 清理车辆GPS历史数据(保留最近2个月,分批删除)
     */
    public void cleanVehicleGpsData() {
        try {
            log.info("开始清理车辆GPS历史数据(保留最近2个月,每批 {} 条)", BATCH_SIZE);
            int totalCount = 0;
            int batchCount;
            int round = 0;
            do {
                batchCount = vehicleGpsService.deleteVehicleGpsBeforeDateBatch(BATCH_SIZE);
                totalCount += batchCount;
                round++;
                log.info("第 {} 批清理完成,本批删除 {} 条,已删除合计 {} 条", round, batchCount, totalCount);
                if (batchCount == BATCH_SIZE) {
                    // 还有数据,稍作休眠再继续
                    Thread.sleep(BATCH_INTERVAL_MS);
                }
            } while (batchCount == BATCH_SIZE);
 
            log.info("清理车辆GPS历史数据完成,共 {} 批,删除 {} 条记录", round, totalCount);
 
            if (totalCount > 0) {
                log.info("开始执行 OPTIMIZE TABLE,回收磁盘空间(此操作耗时较长,请勿中断)");
                vehicleGpsService.optimizeVehicleGpsTable();
                log.info("OPTIMIZE TABLE 执行完成");
            } else {
                log.info("本次无可清理的记录,跳过 OPTIMIZE TABLE");
            }
        } catch (Exception e) {
            log.error("清理车辆GPS历史数据异常", e);
        }
    }