Scheduling temp file and cache directory cleanup

Age-based deletion of stale temp/cache files — and why /tmp itself is probably already handled.

The problem

On most systemd-based distros, /tmp is already cleaned up by systemd-tmpfiles (see /etc/tmpfiles.d/tmp.conf, typically clearing files untouched for 10 days), so a cron job that also purges /tmp is redundant at best and, if its age threshold is shorter than tmpfiles.d's, can delete files another process is still relying on sooner than the OS-level default would.

The real remaining case is application-specific scratch or cache directories that nothing else cleans — upload staging directories, rendered-PDF caches, build artifact directories. The classic bug there is a `find -delete` age filter using the wrong comparison (`-mtime -7` deletes everything modified in the last 7 days — the opposite of what's intended) or matching directories as well as files and removing something still in use.

Check systemd-tmpfiles before adding a cron job for /tmp itself.

Run `cat /etc/tmpfiles.d/tmp.conf` (or `systemd-tmpfiles --cat-config`) to see the existing age-based cleanup rule before writing your own for the same directory. Reserve a cron job for directories systemd-tmpfiles doesn't manage — usually somewhere under your application's own data path, not /tmp.

Recommended schedule

0 3 * * *

Once daily, off-peak, is enough for most scratch-directory cleanup. Faster-filling directories (high-volume upload staging) may need hourly — see /cron for other intervals.

Example crontab entry

# norc: cleanup-scratch Purge stale upload staging files
0 3 * * * /usr/bin/find /var/lib/myapp/staging -type f -mtime +7 -delete >> /var/log/cleanup.log 2>&1

Failure modes to watch for

  • Inverted -mtime sign (`-mtime -7` instead of `+7`) deleting everything recent instead of everything stale.
  • Duplicating a systemd-tmpfiles rule with a shorter threshold, deleting files an OS-level cleanup pass would have left alone longer.
  • Deleting a file another process currently has open — usually harmless on Linux (the inode stays until the handle closes) but confusing when df doesn't reflect freed space until that process exits or restarts.
  • No `-type f`, so the same find also matches and removes directories the application expects to exist, breaking it on next write.

How norc helps

norc keeps the tagged crontab line and its run history visible next to every other scheduled job on the box, so it's obvious at a glance whether cleanup is one of the OS's jobs or one of yours.