Automating Tasks with systemd timers
Automating Tasks with systemd timers
Automating repetitive tasks is a key part of system administration, and traditionally, cron has been the go-to tool for this purpose. However, systemd timers offer a more powerful and flexible alternative. In this post, we’ll walk through setting up a systemd timer to run a script hourly on Debian 12.
Prerequisites
Make sure you have the following:
- A script you want to run periodically. For this example, we’ll use
/home/admin/bin/backup.sh. - Root privileges to create and manage
systemdservice and timer files.
Step-by-Step Guide
1. Create the Service File
First, we need to create a systemd service file that specifies the task we want to run. This file will define the script to execute, the user to run it as, and the working directory.
Run the following command to create the service file:
sudo nano /etc/systemd/system/backup.service
Add the following content to the file:
[Unit]
Description=Run backup script hourly
[Service]
User=admin
WorkingDirectory=/home/admin
ExecStart=/home/admin/bin/backup.sh
2. Create the Timer File
Next, create a timer file that tells systemd when to run the service. For an hourly schedule, we can use the OnCalendar directive.
Run the following command to create the timer file:
sudo nano /etc/systemd/system/backup.timer
Add the following content to the file:
[Unit]
Description=Run backup.service hourly
[Timer]
OnCalendar=hourly
Persistent=true
[Install]
WantedBy=timers.target
The OnCalendar=hourly directive schedules the job to run every hour. The Persistent=true directive ensures the job will run as soon as possible if the system was off at the scheduled time.
3. Enable and Start the Timer
Enable and start the timer to ensure it runs automatically:
sudo systemctl enable backup.timer
sudo systemctl start backup.timer
4. Verify the Timer
Check the status of the timer to ensure it’s running correctly:
sudo systemctl status backup.timer
You should see output indicating that the timer is active and when it is next scheduled to run.
5. List All Timers
To view all active timers, use the following command:
systemctl list-timers
This will list all active timers, their next run time, and their last run time.
Conclusion
Using systemd timers on Debian 12 is a robust and flexible way to schedule periodic tasks. Unlike cron, systemd timers offer more features and finer control over job execution, including the ability to specify the user and working directory. By following the steps above, you can easily set up an hourly job to automate your tasks.
Happy automating!