java 每天23点定时删除某个Folder下的文件

阅读 69

2023-08-17

import java.io.IOException;
import java.nio.file.*;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class FileDeletionExample {
    public static void main(String[] args) {
        // 指定文件夹路径
        String folderPath = "E:/pdt/aa/08-17";
        
        // 获取当前日期和目标时间(每天23点)
        LocalDate currentDate = LocalDate.now();
        LocalTime targetTime = LocalTime.of(23, 0, 0);
        
        // 构造触发删除的日期时间对象
        LocalDateTime targetDateTime = LocalDateTime.of(currentDate, targetTime);

        // 计算初始延迟时间和循环周期
        long initialDelay = LocalDateTime.now().until(targetDateTime, ChronoUnit.SECONDS);
        long period = 24 * 60 * 60;  // 24小时
        
        // 创建ScheduledExecutorService
        ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
        
        // 定时执行删除操作
        executorService.scheduleAtFixedRate(() -> {
            try {
                deleteFiles(folderPath);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }, initialDelay, period, TimeUnit.SECONDS);
    }

    private static void deleteFiles(String folderPath) throws IOException {
        // 创建Path对象
        Path directory = Paths.get(folderPath);
        
        // 遍历文件夹下的所有文件并删除
        try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(directory)) {
            for (Path path : directoryStream) {
                if (Files.isRegularFile(path)) {
                    Files.delete(path);  // 删除文件
                }
            }
        }
    }
}

这段代码做了以下几个步骤:

  1. 构造了每天的目标时间,即每天的23点。
  2. 计算当前时间到目标时间的初始延迟时间和循环周期。初始延迟时间是当前时间到目标时间的秒数差值,循环周期为24小时(24 * 60 * 60秒)。
  3. 使用ScheduledExecutorService创建一个单线程的定时任务执行器。
  4. 使用scheduleAtFixedRate方法,按照设定的循环周期触发定时任务。定时任务会在每天的目标时间执行,并调用deleteFiles方法进行文件删除操作。

精彩评论(0)

0 0 举报