通过定时任务,定时清理本地磁盘过期文件

需求:
项目中临时存储的文件,在本地生成临时文件,需要周期性特定时间执行,进行本地文件清理

功能实现:

1、添加定时任务注解

在springboot项目启动类中添加@EnableScheduling注解,表明开启定时任务

@SpringBootApplication
@EnableScheduling //开启定时任务
public class MainApplication {

    public static void main(String[] args) {
        SpringApplication.run(MainApplication.class, args);
    }
}

2、新建class类

要在任务的类上写@Component表明配置类
要在任务方法上写@Scheduled表明执行时间


import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;


@Slf4j
@Component
public class DeleteFilesUtil {


    /**
     * 每周星期天凌晨1点执行,清理本地磁盘大于7天的音频文件
     */
    @Scheduled(cron = "0 0 1 ? * L")
    public void checkClenFile() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        log.info("======定时清理文件任务开始于:{}", sdf.format(new Date()));
        int howDays = 7;//文件过期天数
        String filePath = "E:/fileload/"; //文件存储路径;
        // 执行删除方法
        int delCount = moveFileToReady(filePath, howDays);
        if (delCount > 0) {
            log.info("======本次从:{}" + filePath + "下清理" + delCount + "份文件");
        } else {
            log.info("======暂时没有要清理的文件");
        }
        log.info("======定时清理文件任务结束于:{}", sdf.format(new Date()));
    }


    /**
     * 定时清理
     * @param filePath 文件目录
     * @param howDays 清理大于的天数
     * @return 删除文件的数量
     */
    public static Integer moveFileToReady(String filePath, int howDays) {
        File srcDir = new File(filePath);
        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();
                    //获取过期天数
                    long days = getDistDates(today, lastModified);
                    if (days >= howDays) {
                        files[i].delete();
                        delTotal++;
                    }
                } catch (Exception e) {
                    log.error("定时清理文件任务失败", e);
                }
            }
        }
        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、执行前先去目录文件查看效果:

效果

4、项目启动方法定时执行,执行效果:

在这里插入图片描述
参考链接

总结:

我是南国以南i记录点滴每天成长一点点,学习是永无止境的!转载请附原文链接!!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值