文件异步延迟删除

1. 场景:

比如,发邮件的时候需要发送附件,发送成功之后,必须把附件删除。
由于邮件发送服务很慢,可能附件被删除了,但是邮件还没有发送成功,最终导致附件发送失败。

2. 解决方案:

异步延迟删除附件。

3. 实例代码

private void delayDeleteFile(File emailAttachment) {
        DeleteLocalTempFileTask task = new DeleteLocalTempFileTask(emailAttachment);
        task.deleteFileInDelay();
    }
import org.apache.commons.lang3.concurrent.BasicThreadFactory;
import java.io.File;
import java.time.LocalDateTime;
import java.util.concurrent.Callable;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author leiming5
 * @description DeleteLocalTempFileTask
 * @date 2023/6/8-11:32
 * Copyright 2022 Lenovo DIBG West Region Service Delivery
 */
public class DeleteLocalTempFileTask {
    private File LocalTempFile;

    public DeleteLocalTempFileTask(File localTempFile) {
        this.LocalTempFile = localTempFile;
    }

    public void deleteFileInDelay() {
        ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(1,
                new BasicThreadFactory.Builder().namingPattern("example-schedule-pool-%d").daemon(true).build());
        executorService.schedule(new Callable<Boolean>() {
            @Override
            public Boolean call() {
                if (LocalTempFile.exists()) {
                    LocalTempFile.delete();
                    System.out.println("文件" + LocalTempFile.getAbsolutePath() + "已删除" + LocalDateTime.now());
                    return true;
                }
                return false;
            }
        }, 30, TimeUnit.SECONDS);
    }
}

你可能感兴趣的:(java,servlet,android)