Having started to switch over to Fedora recently (as well as CoreOS), I needed to figure out how to run jobs at certain times and/or intervals. On an OS like Ubuntu this is accomplished using Cron. Cron is the worlds largest pain in the ass, that is at least in comparison to how easy it is to create timers under Systemd.

For this example, we're going to set up a timer that runs every minute and then create a service that attaches and uses that timer.

Creating the timer

A timer is just like any other unit file except it has a [Timer] section. It looks a little bit like this:

/etc/systemd/system/minute-timer.timer

[Unit]
Description=Minute Timer

[Timer]
OnBootSec=5min
OnCalendar=*:0/1
Unit=minute-timer.target

[Install]
WantedBy=basic.target

Systemd is pretty power with its OnCalendar function. In this case we're telling it to run every minute, but we could get REALLY specific if we wanted. Have a look at the docs to learn more about whats possible.

Now that we have a timer, we need to create a target that will be used by our actual services.

/etc/systemd/system/minute-timer.target

[Unit]
Description=Minute Timer Target
StopWhenUnneeded=yes

Lets create a test service now that will simply print the current date each time it is run

/etc/systemd/system/testservice.service

[Unit]
Description=Prints the date every minute
Wants=minute-timer.timer

[Service]
ExecStart=/bin/date

[Install]
WantedBy=minute-timer.target

Start your timers

Now that we have our timers and test service created, we need to start everything using systemctl

systemctl enable /etc/systemd/system/minute-timer.timer
systemctl start  /etc/systemd/system/minute-timer.timer

systemctl enable /etc/systemd/system/testservice.service

Now if everything goes as planned, we can watch the logs of our service print the date every minute

> journalctl -f -u testservice.service

Jul 07 21:24:00 ip-10-10-10-10 systemd[1]: Starting Prints the date every minute...
Jul 07 21:24:00 ip-10-10-10-10 systemd[1]: Started Prints the date every minute.
Jul 07 21:24:00 ip-10-10-10-10 date[20887]: Mon Jul  7 21:24:00 UTC 2014
Jul 07 21:25:00 ip-10-10-10-10 systemd[1]: Starting Prints the date every minute...
Jul 07 21:25:00 ip-10-10-10-10 systemd[1]: Started Prints the date every minute.
Jul 07 21:25:00 ip-10-10-10-10 date[20889]: Mon Jul  7 21:25:00 UTC 2014
Jul 07 21:26:00 ip-10-10-10-10 systemd[1]: Starting Prints the date every minute...
Jul 07 21:26:00 ip-10-10-10-10 systemd[1]: Started Prints the date every minute.