Recurring task with systemd

I know, I know, cron is much easier but I was playing around with systemd and timers were one of the things that weren't very clear to me. So this is what I finally ended up with to run several backup tasks every sunday with systemd.

Write unit-files

To create a recurring task in systemd the following unit-files are needed. A timer file which will trigger a target file at set times which in turn will trigger one or more service files. On ubuntu the files should be created in /lib/systemd/system.

  1. weekly-backup.timer

     Description=Weekly backup timer  
     OnCalendar=Sun *-*-* 14:00:00
     [Install] will make sure the timer is enabled when the system starts.
Unit defines the unit that will be triggered when the timer is activated.
Persistant=true makes sure the target is triggered if the system happened to be shut down when the timer should have triggered. (See Persistant)
OnCalendar defines the time(s) this timer file should trigger the target unit. I this case it will trigger on Sunday on any date at 14:00. (See systemd.time)


     Description=Weekly backup

StopWhenUnneeded=yes will make sure the target is set to inactive when it's finished and the timer will be able to trigger it again the next time the timer activates.

  1. backup-app.service
    First service.

     Description=Backup app  
     [Install] will make sure this service will start when is triggered by the timer.
ExecStart defines the script or program that should be run.

  1. backup-data.service
    Second service, all services having will be triggered.

     Description=Backup data  

Enable units

  1. Enable the services
    systemctl enable backup-app.service
    systemctl enable backup-data.service

  2. Enable and start the timer
    systemctl enable weekly-backup.timer
    systemctl start weekly-backup.timer

That's it.


  1. You can skip the targetfile and set Unit=backup-app.service directly in the timer file if backup-app.service is the only service you want to run on the timer. In this case you should also remove the install section from the service file. ↩︎