I am looking to improve an application that writes log files to a particular location. I have a method that looks for the files in a folder and then uses several loops to find the oldest file and delete it.
This is an old method I wrote years ago and I am looking at improving how I find the oldest and then delete it to reduce the time this takes. I could have thousand or so files of at least 2Mb to 12 Mb in size.
dim oldest as FolderItem = nil
for each f as FolderItem in myFolder.Children
if not f.IsFolder and f.Name.EndsWith(".log") then
if oldest = nil or f.ModificationDate < oldest.ModificationDate then oldest = f
end if
next
if oldest <> nil then oldest.Delete
Platform is OSX using Big Sur XOJO 2021 r1. I have been updating to get daemons to run on the new XOJO RAD looking to reduce CPU % and memory. Originally I had a memory leak because I used the old way of calling using MyApplication with no Super having Initialize, Idle, Final for Methods. I finally fixed that and started looking at other improvements.
@Paul_Rodman After your post I took a look at my previous method that did this work. I have another area that was similar. So I made a few modifications and used that routine there as well. This works on several terminal apps that act as a daemon all working together using inter processor communications.
That suggestion really helped and I have implemented in all solutions.
Here is a bit of what I used in a final version.
If Current_Log_file.Count >= 500 Then
Var oldest As FolderItem = Nil
For Each f in Current_Log_file.Children
If not f.IsFolder and f.Name.EndsWith(".log", ComparisonOptions.CaseSensitive, Locale.Current) Then
If oldest = nil or f.ModificationDate < oldest.ModificationDate Then oldest = f
End If
Next
Var this_file_was_deleted As String = oldest.Name
Try
If oldest <> Nil Then oldest.Delete
// Post File was deleted to Running_Log
Catch e As IOException
// Post error to Error_Log
End
End If
Nice code, but you’re accessing oldest.ModificationDate whenever you come across another log file; what if “oldest” disappears or otherwise gets modified while your loop executes?
I’d suggest you use a variable to hold the date.