现在有一个需求,定时清除服务器指定目录下的缓存文件,写了定时任务,代码如下:
/** * @description 每天凌晨执行一次 */ @Scheduled(cron = "0 0 0 * * ?") public void cleanupTempLabelFolder() { String folderPath = "tempLabel"; File folder = new File(folderPath); File[] files = folder.listFiles(); if (files != null) { for (File file : files) { try { BasicFileAttributes attr = Files.readAttributes(file.toPath(), BasicFileAttributes.class); FileTime creationTime = attr.creationTime(); LocalDate fileCreationDate = creationTime.toInstant().atZone(ZoneId.systemDefault()).toLocalDate(); LocalDate oneWeekAgo = LocalDate.now().minus(7, ChronoUnit.DAYS); if (fileCreationDate.isBefore(oneWeekAgo)) { if (file.delete()) { log.info("Deleted file: " + file.getName()); } else { log.error("Failed to delete file: " + file.getName()); } } } catch (Exception e) { e.printStackTrace(); } } } }此处以清理七天前的文件为例,也可以做成xxl-job任务注册执行。