springboot定期清理文件

springboot定期清理文件

springboot定期清理文件

搬砖需求 今天在使用springboot清理文件 实现使用ThreadPoolTaskScheduler定时触发动态执行需要清理根据文件创建时间来清理指定多少天之前的文件仅供大家参考直接上代码

配置个ThreadPoolTaskScheduler bean

@Bean(“taskScheduler”)
public TaskScheduler taskScheduler() {
ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler();
threadPoolTaskScheduler.setPoolSize(10);
threadPoolTaskScheduler.setWaitForTasksToCompleteOnShutdown(true);
return threadPoolTaskScheduler;
}

  1. 触发定时任务

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;
}

}

  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值