feat(scheduled): 添加日志数据清理定时任务

- 新增 LogDataCleanSchedule 定时任务类
- 实现每天凌晨2点自动清理六个月前的日志数据
- 使用 cron 表达式 "0 0 2 * * ?" 配置执行时间
- 通过 LambdaQueryWrapper 构造删除条件
- 添加任务执行日志记录和异常处理
- 继承 BaseSchedule 实现任务幂等性和缓存控制
This commit is contained in:
2025-11-21 10:43:05 +08:00
parent 6704a1eae8
commit e38b1dbbfb

View File

@@ -0,0 +1,55 @@
package com.fizz.business.scheduled;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fizz.business.domain.LogData;
import com.fizz.business.service.LogDataService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
/**
* 日志数据清理定时任务
* 每天凌晨2点执行删除六个月前的日志数据
*/
@Slf4j
@Component
public class LogDataCleanSchedule extends BaseSchedule {
@Autowired
private LogDataService logDataService;
/**
* 每天凌晨2点执行日志清理任务
* cron表达式: 秒 分 时 日 月 周
*/
@Scheduled(cron = "0 0 2 * * ?")
public void cleanOldLogData() {
String taskName = "日志数据清理任务";
String cacheKey = "log_data_clean_task";
execute(taskName, 3600, cacheKey, () -> {
actionCatchException(() -> {
// 计算六个月前的时间
LocalDateTime sixMonthsAgo = LocalDateTime.now().minusMonths(6);
log.info("开始清理六个月前的日志数据,截止时间: {}", sixMonthsAgo);
// 删除六个月前的日志数据
LambdaQueryWrapper<LogData> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.lt(LogData::getTimestamp, sixMonthsAgo);
Long deletedCount = logDataService.count(queryWrapper);
boolean result = logDataService.remove(queryWrapper);
if (result) {
log.info("日志数据清理完成,共删除 {} 条记录", deletedCount);
} else {
log.warn("日志数据清理失败");
}
});
});
}
}