Configuring Timers
Systemd timers provide a powerful mechanism to schedule services to run at specific times or intervals. By combining .timer unit files with corresponding .service units, you can automate recurring tasks such as backups, system checks, or maintenance routines. This section demonstrates how to create, manage, and troubleshoot systemd timers.
Understanding Timer Unit Files¶
A .timer unit file defines when a service should be triggered. It includes two main sections:
- [Unit]: Describes the timer's purpose and dependencies.
- [Timer]: Specifies scheduling rules, such as intervals or calendar-based triggers.
Example structure:
[Unit]
Description=Daily System Check
[Timer]
OnCalendar=daily
Unit=syscheck.service
[Install]
WantedBy=timers.target
Key timer options in the [Timer] section:
- OnCalendar: Schedule based on dates/times (e.g., daily, * * * * * for cron-like syntax).
- OnUnitActiveSec: Trigger after a service has been active for a duration.
- OnBootSec: Trigger after a delay following system boot.
- AccuracySec: Define how precisely the timer should align with the schedule.
Creating a Timer¶
-
Define the service: Create a
.servicefile for the task. For example, a script that logs system metrics: -
Create the timer: Write a
.timerfile to schedule the service. To run the service every hour: -
Enable and start the timer:
The AccuracySec option ensures the timer aligns with the specified interval, even if delayed.
Managing Timers¶
Use systemctl to interact with timers:
- List active timers:
-
Trigger a timer immediately:
Use--nowto force execution without waiting for the next scheduled time: -
Modify a timer: Edit the
.timerfile and reload systemd: -
Disable or stop a timer:
Troubleshooting Timers¶
Common issues and solutions: - Timer not triggering: Check logs with:
Ensure the service unit (sysmetrics.service) exists and is valid.
- Incorrect scheduling: Verify OnCalendar syntax matches systemd's format (e.g., * * * * * for every minute).
- Permissions: Ensure the timer unit file is owned by root and has correct permissions (-rw-r--r--).
Key takeaways¶
- Timers link to services: A
.timerunit must reference a valid.serviceunit. - Use
OnCalendarfor flexibility: Cron-like syntax enables precise scheduling. - Monitor with
systemctl list-timers: Track active and pending timer events. - Debug with
journalctl: Logs reveal errors in timer or service execution.