Create a model class to store image loading information, such as imagePath and uploadedTime .
class UploadedImage { private Path imagePath; private long uploadedTime; public UploadedImage(Path imagePath, long uploadedTime) { this.imagePath = imagePath; this.uploadedTime = uploadedTime; } public Path getImagePath() { return imagePath; } public long getUploadedTime() { return uploadedTime; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final UploadedImage other = (UploadedImage) obj; if (!Objects.equals(this.imagePath, other.imagePath)) { return false; } if (this.uploadedTime != other.uploadedTime) { return false; } return true; } }
Create an UploadedImage object for each image upload and save them in a global ArrayList.
//... ArrayList<UploadedImage> imageBucket = new ArrayList<>(); //... public synchronized void uploadingImage(Path imagePath, long uploadedTime){ imageBucket.add(new UploadeImage(imagePath, uploadedTime)); }
And prepare the stream to perform file deletion, as shown below.
boolean deletionOff = false; new Thread(new Runnable() { private final long IMAGE_LIFE_TIME = 1000 * 60 * 15;//fifteen minutes @Override public void run() { while (!deletionOff) { //this fore-each will retrieve objects from OLDEST to NEWEST for (UploadedImage uploadedImage : imageBucket) { //finds the elapsed time since the upload of this image long timeElapsed = System.currentTimeMillis() - uploadedImage.getUploadedTime(); if (timeElapsed >= IMAGE_LIFE_TIME) { //following commands will execute only if the image is eligible to delete try { Files.delete(uploadedImage.getImagePath()); } catch (IOException ex) { // } finally { imageBucket.remove(uploadedImage); } } else { //this block will execute when IMAGE_LIFE_TIME is //bigger than the elapsed time which means the //selected image only have //(IMAGE_LIFE_TIME - timeElapsed) of time to stay alive //NOTE : //there is no need to check the next UploadedImage //objects as they were added to the list after the //currently considering UploadedImage object, //which is still has some time to stay alive try { Thread.sleep(IMAGE_LIFE_TIME - timeElapsed); break; } catch (InterruptedException ex) { // } } } } } }).start();
source share