In this lesson, you will learn how to automate service execution by using Systemd Path units to monitor filesystem changes instead of relying on fixed schedules.
The Logic of Path Units
While Timers are perfect for recurring tasks, they are inefficient when you need to react to a specific event, such as a configuration file being updated or a data file being dropped into a directory. A Path unit acts as an event listener; it uses the kernel's inotify subsystem to watch a target file or directory and triggers an associated service unit the moment a defined condition is met.
Structuring the Trigger
A Path unit requires two components: the .path file itself and a corresponding .service file with the exact same name.
For example, if you want to run a script whenever a file appears in /srv/import/, create /etc/systemd/system/file-watcher.path:
[Unit]
Description=Watch for new files in import directory
[Path]
PathChanged=/srv/import/
# Or use PathExists= to watch for a specific file
[Install]
WantedBy=multi-user.target
When PathChanged detects an activity in that directory, Systemd automatically starts file-watcher.service. Notice that you do not need to tell the Path unit which service to run; by default, it looks for a service file sharing its prefix (e.g., file-watcher.path triggers file-watcher.service).
Why Use Path Units Over Polling?
If you used a Cron job to check for files every minute, you would waste CPU cycles during idle periods and incur a delay between the file appearing and your script running. Path units are event-driven, meaning the system remains idle until the kernel signals that the filesystem state has changed. This is cleaner, faster, and more resource-efficient.
To activate your new trigger, remember to reload the daemon (systemctl daemon-reload) and enable the path unit (systemctl enable --now file-watcher.path). If you modify the configuration later, use systemctl restart to refresh the listener.
Key Takeaway: Path units decouple execution logic from polling intervals by using kernel-level events to trigger services immediately upon filesystem changes.