How guarantee the file will be deleted after automatically some time? [closed]

喜夏-厌秋 提交于 2019-12-03 17:34:23

I don't think the approach with using jmv shutdown hooks is reliable and it seems not what you are looking for. I would suggest creating a class with map of files you want to schedule for deletion and have a callback that will allow to postpone deletion time when called:

private Map<Path, ScheduledFuture> futures = new HashMap<>();

private ScheduledExecutorService executor = Executors.newScheduledThreadPool(Runtime.getRuntime().availableProcessors());

private static final TimeUnit UNITS = TimeUnit.SECONDS; // your time unit

public void scheduleForDeletion(Path path, long delay) {
    ScheduledFuture future = executor.schedule(() -> {
        try {
            Files.delete(path);
        } catch (IOException e) {
            // failed to delete
        }
    }, delay, UNITS);

    futures.put(path, future);
}

public void onFileAccess(Path path) {
    ScheduledFuture future = futures.get(path);
    if (future != null) {

        boolean result = future.cancel(false);
        if (result) {
            // reschedule the task
            futures.remove(path);
            scheduleForDeletion(path, future.getDelay(UNITS));
        } else {
            // too late, task was already running
        }
    }
}

You can use Timer() class. It basically allows you to specify a Timer with a certain delay and a TimerTask. Timer executes the TimerTask after the delay is up and runs your code. You just have to set the file path for the TimerTask programmaticaly.

Here's Timer documentation.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!