Course contentsShow
← Linux
Lesson 1298 of 1,81911. Automation and System SchedulingFree lesson

Event-driven Cleanup of Temporary Files

Use systemd-tmpfiles to manage expiration and deletion of ephemeral data.

In this lesson, you will learn how to leverage systemd-tmpfiles to automate the cleanup of ephemeral data based on file age and system events rather than traditional cron jobs.

Why Avoid Cron for Cleanup?

While you have mastered transitioning cron jobs to timers, using them for file cleanup often leads to "check-and-delete" logic that is inefficient. You would have to write a script that iterates through directories, checks timestamps, and removes files. systemd-tmpfiles handles this declaratively, allowing the system to process cleanup rules natively at boot or on a schedule without needing a custom script.

Defining Cleanup Rules

The utility reads configuration files from /etc/tmpfiles.d/. Each line in these files defines a directory, the cleanup action, the age threshold, and the file type.

For example, to automatically remove files in /var/cache/myapp that haven't been accessed in 3 days, create /etc/tmpfiles.d/myapp-cache.conf:

#Type Path               Mode User Group Age  Argument
d     /var/cache/myapp   0755 root root  -    -
e     /var/cache/myapp/* -    -    -     3d   -
  • d: Ensures the directory exists.
  • e: Cleans up files and directories inside the path, but does not delete the directory itself, provided they are older than the age argument (3d).

How It Triggers

You don't need to manually start a timer for this. systemd-tmpfiles integrates with the system boot process. When the system starts, systemd-tmpfiles-setup.service processes these rules. If you want to trigger these cleanups periodically without a full reboot, you can rely on the system-provided systemd-tmpfiles-clean.timer. This timer activates systemd-tmpfiles-clean.service, which parses your /etc/tmpfiles.d/ files and performs the deletions as defined.

By using this approach, you decouple the cleanup logic from your application code. The system handles the "event"—the passage of time—and executes the cleanup safely, ensuring your storage remains optimized without leaving orphaned processes or manual scripts prone to failure.

Key Takeaway: Use declarative tmpfiles.d configurations to let the system manage ephemeral storage lifecycles automatically, replacing imperative scripts with robust, native cleanup rules.