package com.vincent.rsf.schedule.schedules; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.vincent.rsf.framework.common.Cools; import com.vincent.rsf.schedule.system.entity.ExportTask; import com.vincent.rsf.schedule.system.service.ExportTaskService; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Value; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import java.io.File; import java.util.Date; import java.util.List; import java.util.Objects; @Slf4j @Component public class ExportTaskCleanupSchedules { private final ExportTaskService exportTaskService; @Value("${rsf.export-task.cleanup-batch-size:200}") private int cleanupBatchSize; public ExportTaskCleanupSchedules(ExportTaskService exportTaskService) { this.exportTaskService = exportTaskService; } @Scheduled( initialDelayString = "${rsf.export-task.cleanup-initial-delay-ms:60000}", fixedDelayString = "${rsf.export-task.cleanup-fixed-delay-ms:3600000}" ) public void cleanupExpiredExportTasks() { List expiredTasks = exportTaskService.list( new LambdaQueryWrapper() .eq(ExportTask::getDeleted, 0) .isNotNull(ExportTask::getExpireTime) .lt(ExportTask::getExpireTime, new Date()) .last("LIMIT " + Math.max(cleanupBatchSize, 1)) ); if (Cools.isEmpty(expiredTasks)) { return; } expiredTasks.forEach(this::deleteTaskFile); exportTaskService.removeByIds(expiredTasks.stream().map(ExportTask::getId).toList()); } private void deleteTaskFile(ExportTask task) { if (task == null || Cools.isEmpty(task.getFilePath())) { return; } try { File file = new File(task.getFilePath()); if (file.exists() && file.isFile() && !file.delete()) { log.warn("导出任务文件删除失败, taskId={}, filePath={}", task.getId(), task.getFilePath()); } } catch (Exception error) { log.warn( "导出任务文件删除异常, taskId={}, filePath={}", task.getId(), Objects.toString(task.getFilePath(), ""), error ); } } }