This can be done using two published functions and a scheduled script. Let's go through it:
1) Create a published function to delete a folder:
function deleteDirectory(directoryToDelete) {
// new up a java.io.File for the folder that was passed into the function
var directory = new java.io.File(directoryToDelete);
// list out all of the files/folders for the given directory
var files = directory.listFiles();
// cycle the files/folders one at a time
if (files !== null && files.length > 0) {
for (var currentFile = 0; currentFile < files.length; currentFile++) {
// if this item is a file and not a directory, then we can just delete it
if (!files[currentFile].isDirectory()) {
files[currentFile].delete();
} else if (files[currentFile].isDirectory()) {
// we need to call back to this same function to delete this folder
deleteDirectory(files[currentFile].getAbsolutePath());
}
}
}
// now that the directory is empty, we can delete it
directory.delete();
}
2) Create a published function to cycle your directory and delete the files or folders based on a cutoffi time.
function deleteFolders(days,folder) {
// calculate the cutoffTime based on how many days you want to retain
var cutoffTime = (new java.util.Date()).getTime() - (days * 24 * 60 * 60 * 1000);
// new up a java.io.File for the folder that was passed into the function
var directory = new java.io.File(folder);
// list out all of the files/folders for the given directory
var files = directory.listFiles();
// cycle the files/folders one at a time
if (files !== null && files.length > 0) {
for (var currentFile = 0; currentFile < files.length; currentFile++) {
// if this item is a file and not a directory, then we can just delete it
if (!files[currentFile].isDirectory()) {
// compare the last modified time to the cutoff time to determine if we are going to delete the file
if (files[currentFile].lastModified() < cutoffTime) {
// REMEMBER: Uncomment the next line after testing so that the file actually gets deleted.
// files[currentFile].delete();
qie.debug('File (' + files[currentFile].getAbsolutePath() + ') would be deleted.');
}
} else if (files[currentFile].isDirectory()) {
// compare the last modified time to the cutoff time to determine if we are going to delete this folder
if (files[currentFile].lastModified() < cutoffTime) {
// REMEMBER: Uncomment the next line after testing so that the directory actually gets deleted.
// deleteDirectory(files[currentFile].getAbsolutePath());
qie.debug('Directory (' + files[currentFile].getAbsolutePath() + ') would be deleted.');
}
}
}
}
}
3) Create a scheduled script on our channel that will call this function on a daily basis.
// delete files/folders from my temp directory that are over 5 days old
deleteFolders(5, 'C:\\Temp\\');
Now I can schedule the script to run every day and keep my temp folder clean.