How to do housekeeping in a berth?

We allow users to upload certain image files to our web server. These files are useless 10-15 minutes after downloading. Is there a way to automatically delete these files, for example. all image files that expire 15 minutes after they are created?

+6
source share
5 answers

I basically configure the quartz scheduler inside my web server using a cron trigger

and the work looked bigger or something like this

public static void deleteFilesOlderThanNdays(int daysBack, String dirWay, org.apache.commons.logging.Log log) { File directory = new File(dirWay); if(directory.exists()){ File[] listFiles = directory.listFiles(); long purgeTime = System.currentTimeMillis() - (daysBack * 24 * 60 * 60 * 1000); for(File listFile : listFiles) { if(listFile.lastModified() < purgeTime) { if(!listFile.delete()) { System.err.println("Unable to delete file: " + listFile); } } } } else { log.warn("Files were not deleted, directory " + dirWay + " does'nt exist!"); } } 

ref: http://www.coderanch.com/t/384581/java/java/Delete-Files-Older-days

0
source

You just answered your question - you will get all the files with the word "expire" in the name and change 15 minutes before the current time and delete them.

Here is the code. This is inefficient, but simple:

 File dir=new File("."); String []expiredFiles=dir.list(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return (name.contains("expired")&& new File(dir,name).lastModified()<System.currentTimeMillis()-15*60*1000); } }); for(String file:expiredFiles){ new File(dir,file).delete(); } 

You can run it every 15 minutes or so. Or, a simpler approach, run it when each request answers and closes, but the thread has not stopped yet. For example, when immediately after closing the output stream to the response object. This does not require large resources, especially when the thread is working and continues to work.

+6
source

There is no such thing in the dock, as mlapeir says. Take a look at the Guavas cache .

Something like this will do the trick, I think:

 Cache<Key, Graph> graphs = CacheBuilder.newBuilder() .maximumSize(1000) .expireAfterWrite(10, TimeUnit.MINUTES) .removalListener(DELETE_FILES_LISTENER) .build(); 
+2
source

I do not think that the berth has a built-in function for this. You can create the GarbageCollector class and schedule file deletion using ScheduledExecutorService:

 public class GarbageCollector { private ScheduledExecutorService service = Executors.newScheduledThreadPool(1); public void scheduleFileDeletion(Path path) { service.schedule(() -> { try { Files.delete(path); } catch (IOException ignored) { } }, 15, TimeUnit.MINUTES); } } 
0
source

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(); 
0
source

Source: https://habr.com/ru/post/987913/


All Articles