Spring 引导任务计划删除数百万个带有父文件夹的旧文件



想要在 50 到 300 天内删除数百万个旧文件,如果我使用简单的 spring 任务,那么删除带有文件夹的文件也会有性能开销。删除再次需要递归方法的文件夹。

什么方法会好,任何建议或解决方案。

我不确定我是否完全理解您的问题,但这里有一个 Spring Boot 应用程序中的计划任务示例,它以递归方式查找所有文件,从根路径开始,然后删除过去 50 天内未修改的任何文件。

此任务每 10 秒运行一次。

@Service
public class FileService {
@Scheduled(fixedDelay = 10000)
public void deleteFilesScheduledTask() throws IOException {
findFiles("C:/testing");
}
public void findFiles(String filePath) throws IOException {
List<File> files = Files.list(Paths.get(filePath))
.map(path -> path.toFile())
.collect(Collectors.toList());
for(File file: files) {
if(file.isDirectory()) {
findFiles(file.getAbsolutePath());
} else if(isFileOld(file)){
deleteFile(file);
}
}
}
public void deleteFile(File file) {
file.delete();
}
public boolean isFileOld(File file) {
LocalDate fileDate = Instant.ofEpochMilli(file.lastModified()).atZone(ZoneId.systemDefault()).toLocalDate();
LocalDate oldDate = LocalDate.now().minusDays(50);
return fileDate.isBefore(oldDate);
}
}

希望这能让您了解如何在自己的应用中实现此功能。