In this lesson, you will learn how to trigger automated tasks in response to system-level power state changes using systemd hooks.
When managing automated infrastructure, you often need to perform actions that aren't just time-based, but state-based. For example, you might need to sync a local database to a remote server right before the system shuts down, or flush a hardware cache immediately after waking from sleep. While Cron is restricted to time intervals, systemd provides specialized targets that act as event hooks for power transitions.
Using Power Hooks
The most common system-level hooks are tied to the suspend.target, hibernate.target, and poweroff.target. By creating a service unit that "wants" these targets, you can execute scripts at critical moments in the power management lifecycle.
To run a script specifically when your machine wakes up from suspend, you create a service unit with the following configuration:
[Unit]
Description=Run cleanup after wake
After=suspend.target
[Service]
Type=oneshot
ExecStart=/usr/local/bin/post-wake-cleanup.sh
[Install]
WantedBy=suspend.target
Understanding the Hook Lifecycle
When you define WantedBy=suspend.target, the system links your service into the dependency chain. Because the service is defined with After=suspend.target, systemd ensures your task triggers as the system completes the transition back to an active state.
You can apply this logic to various states:
pre-shutdown.target: Use this to trigger final data integrity checks or logs before the kernel halts.hybrid-sleep.target: Use this to ensure your automation handles both disk and RAM persistence states.
The power of this approach lies in its reliability. Unlike a background script polling for status changes, these hooks are managed by the system init process, ensuring they are queued and executed as part of the formal power transition sequence. This prevents "race conditions" where a system might power down before your cleanup automation finishes its work.
Key Takeaway: Leverage systemd targets as event-driven hooks to guarantee your automation runs reliably during critical power state transitions.