If the directory is updating every 5 secs then surely it's the same thing?
Yes and No
The code as stands is calling off single details entry by entry
in code and working out if it's the latest timestamped file from the directory time attributes, so its making two calls to the underlying OS, (i) to get the name (ii) to get the OS timestamp. There is no indication that the OS will perform
in any particular manner with regard to whether it goes and reads the filesystem content of the HD for each call, or finds the information in cached memory, and you have to walk the entire set of files each time to manually determine the 'latest' entry. Since there is the possibility under heavy load that new file is injected while you are walking current list (because you're taking > 5s to do so), and the specs for ReadDir indicate that the 'next file (details) according to [underlying] directory order' is delivered, you may actually miss the later posting(s), until such time as the loop execution drops below 5s
Collecting the entire directory contents in one hit may/
should be a faster operation (from the OS perspective). Once you've been given the entire set, the sort call and top/tail selection should be memory based. Since you intimate that the filename has embedded timestamp information, there is no need to query the filesystem for the OS timestamp - derive the 'latest' from the filename ordering returned by the sort.
Either way, unless you're doing code/other stuff elsewhere that's not shown , the fundemental issue that you need to
shift the old stuff. You're posting images at 12 per minute/720 hour/17,280 day/120960 week/483840 ~'month' - with the best will in the world, no servers gonna like walking 1/2 a million plus entries in single folder every 5 seconds.
You only need the 'latest' to show, + 1 prior at maximum...anything over 10+s old gets shifted. Move it to year\month\day filesystem structure, giving you the ability to quickly select and ditch whole period content. If people want to see old images, implement display from year\month\day folder based on datepicker selection...
Best. P.