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

     [Unit]
     Description=Weekly backup timer  
     [Timer]
     OnCalendar=Sun *-*-* 14:00:00
     [Persistant=true](http://www.freedesktop.org/software/systemd/man/systemd.timer.html#Persistent=)=true
     Unit=weekly-backup.target  
     [Install]
     WantedBy=default.target
    

WantedBy=default.target 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)

  1. weekly-backup.target[1]

     [Unit]
     Description=Weekly backup
     StopWhenUnneeded=yes
    

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.

     [Unit]
     Description=Backup app  
     [Service]
     ExecStart=/usr/local/bin/backupapp  
     [Install]
     WantedBy=weekly-backup.target
    

WantedBy=weekly-backup.target will make sure this service will start when weekly-backup.target is triggered by the timer.
ExecStart defines the script or program that should be run.

  1. backup-data.service
    Second service, all services having WantedBy=weekly-backup.target will be triggered.

     [Unit]
     Description=Backup data  
     [Service]
     ExecStart=/usr/local/bin/backupdata  
     [Install]
     WantedBy=weekly-backup.target
    

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.

Notes:


  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. ↩︎