CleanJob.java 1.56 KB
package com.viontech.fanxing.ops.runner;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ArrayUtil;
import com.viontech.fanxing.commons.config.VionConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZoneOffset;

/**
 * .
 *
 * @author 谢明辉
 * @date 2022/1/4
 */

@Component
@Slf4j
public class CleanJob {

    @Resource
    private VionConfig vionConfig;

    @Scheduled(cron = "0 0 9 * * ?")
    public void cleanTemp() {
        try {
            log.info("开始清理2天前的临时文件");
            long today = LocalDate.now().toEpochDay();
            File tempDir = new File(vionConfig.getImage().getPath() + "/temp)");
            File[] files = tempDir.listFiles();
            if (ArrayUtil.isNotEmpty(files)) {
                for (File file : files) {
                    long l = file.lastModified();
                    LocalDate localDate = Instant.ofEpochMilli(l).atOffset(ZoneOffset.of(ZoneId.systemDefault().getId())).toLocalDate();
                    if (today - localDate.toEpochDay() >= 2) {
                        log.info("删除文件:{}", file.getName());
                        FileUtil.del(file);
                    }
                }
            }
            log.info("完成清理2天前的临时文件");
        } catch (Exception e) {
            log.error("", e);
        }
    }
}