zhou zhou
2 天以前 34d36a15f339d331d668d4063cfdff50cffa5800
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
59
60
61
62
63
64
65
66
67
68
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<ExportTask> expiredTasks = exportTaskService.list(
                new LambdaQueryWrapper<ExportTask>()
                        .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
            );
        }
    }
}