Using a Systemd Timer as a Cron Job

· jswank's blog

#linux #systemd

I want to make backups on a regular basis, allow the backup task to be run on-demand, and run in a specific environment (directory, environment variables, etc). I aleady have a script I can run to make the backup. The host uses systemd for service management.

# Procedure

Create a script to do the backup. This is system dependent: for purposes of this article, /path/to/backup/script is the backup script. It runs as the user infinite from the home directory /home/infinite.

Create a service unit file which runs the backup script. Create a service unit file at /etc/systemd/system/backup.service.

[Unit]
Description=Backup the database

[Service]
User=infinite
Group=infinite
Type=oneshot
WorkingDirectory=/home/infinite
ExecStart=/path/to/backup/script

[Install]
WantedBy= multi-user.target

Validate the service unit. Run the service and confirm it works as expected.

1$ sudo systemctl start backup

Create a timer unit to trigger the service. Create a timer unit at /etc/systemd/system/backup.timer like the following, which runs the backup service defined above at 4:00AM on a daily basis.

[Unit]
Description=Backup the database daily

[Timer]
OnCalendar=*-*-* 04:00:00
Persistent=true
Unit=backup.service

[Install]
WantedBy=timers.target

Enable the timer and start it:

1$ sudo systemctl enable backup.timer
2$ sudo systemctl start backup.timer

Validate the timer will execute.

1$ systemctl list-timers backup.timer
2NEXT                         LEFT     LAST                         PASSED       UNIT          ACTIVATES
3Tue 2023-03-28 04:00:00 UTC  6h left  Mon 2023-03-27 20:41:33 UTC  1h 7min ago  backup.timer  backup.service

# Alternative Procedure

Add a line to the crontab. Use the command crontab -e to add a line like the following:

0 4 * * * /path/to/backup/script

Validate that cron sees the new entry.

1$ crontab -l

# Comments

Systemd allows for a high degree of control when executing automated tasks, such as customizing the environment with resource limits and permissions and secure access of secret information like credentials. Logging and debugging of tasks uses the same toolset and processes as running other systemd services.

If this degree of control is not required, using cron is a simple and time-tested alternative.

# References