springboot定期清理文件
springboot定期清理文件
搬砖需求 今天在使用springboot清理文件 实现使用ThreadPoolTaskScheduler定时触发动态执行需要清理根据文件创建时间来清理指定多少天之前的文件仅供大家参考直接上代码
配置个ThreadPoolTaskScheduler bean
@Bean(“taskScheduler”)
public TaskScheduler taskScheduler() {
ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler();
threadPoolTaskScheduler.setPoolSize(10);
threadPoolTaskScheduler.setWaitForTasksToCompleteOnShutdown(true);
return threadPoolTaskScheduler;
}
- 触发定时任务
package com.cre.seal.task;
import com.cre.seal.util.DeleteFilesUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.text.SimpleDateFormat;
import java.util.Date;
@Slf4j
@Component
public class SchedulingTask {
private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
@Value("${templateExport.Path}")
private String attachPath;
@Scheduled(cron = "${time.cron}")
@Async("taskScheduler")
public void checkClenFile() {
log.info("======定时清理文件任务开始于:{}", sdf.format(new Date()));
String filePath = attachPath;
// 删除多少天之前文件
int delCount = DeleteFilesUtils.moveFileToReady(filePath, 7);
if (delCount > 0) {
log.info("======本次从:{}" + filePath + "下清理" + delCount + "份文件");
} else {
log.info("======暂时没有要清理的文件");
}
log.info("======定时清理文件任务结束于:{}", sdf.format(new Date()));
}
}
清理文件工具
package com.cre.seal.util;
import java.io.File;
import java.util.Calendar;
import java.util.Date;
public class DeleteFilesUtils {
public static Integer moveFileToReady(String fromDir,int howDays ) {
File srcDir = new File(fromDir);
if (!srcDir.exists()) {
return 0;
}
File[] files = srcDir.listFiles();
if (files == null || files.length <= 0) {
return 0;
}
// 删除文件总数
int delTotal = 0;
Date today = new Date();
for (int i = 0; i < files.length; i++) {
if (files[i].isFile()) {
try {
File ff = files[i];
long time = ff.lastModified();
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(time);
Date lastModified = cal.getTime();
//(int)(today.getTime() - lastModified.getTime())/86400000;
long days = getDistDates(today, lastModified);
// 删除多少天前之前文件
if (days >= howDays) {
files[i].delete();
delTotal++;
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
return delTotal;
}
/**
* @param startDate
* @param endDate
* @return
*/
public static long getDistDates(Date startDate, Date endDate) {
long totalDate = 0;
Calendar calendar = Calendar.getInstance();
calendar.setTime(startDate);
long timestart = calendar.getTimeInMillis();
calendar.setTime(endDate);
long timeend = calendar.getTimeInMillis();
totalDate = Math.abs((timeend - timestart)) / (1000 * 60 * 60 * 24);
return totalDate;
}
}