The more I use it, the more I like using SystemD to manage services. It is sometimes verbose, but in general, it is very easy to use and very powerful. It can restart failed services, start services automatically, handle logging and rolling for simplistic services, and much more.
SystemD Instead of Cron
Recently, I had to take a SystemD service and make it run on a regular timer. So, of course, my first thought was using cron… but I’m not a particularly big fan of cron for reasons I won’t go into here.
I found out that SystemD can do this as well!
Creating a SystemD Timer
Let’s say you have a (very) simple service defined like this in SystemD (in /etc/systemd/system/your-service.service):
[Unit] Description=Do something useful. [Service] Type=simple ExecStart=/opt/your-service/do-something-useful.sh User=someuser Group=someuser
Then you can create a timer for it by creating another SystemD file in the same location but ending with “.timer” instead of “.service”. It can handle basically any interval, can start at reboot, and can even time tasks based on the reboot time.
[Unit] Description=Run service once daily. [Timer] OnCalendar=*-*-* 00:30:00 Unit=your-service.service [Install] WantedBy=multi-user.target
Once the timer file is made, you can enable it like to:
sudo systemctl daemon-reload sudo systemctl enable your-service.timer sudo systemctl start your-service.timer
After this, you can verify the timer is working and check its next (and later on, previous) execution time with this command:
$> systemctl list-timers --all NEXT LEFT LAST PASSED UNIT ACTIVATES Tue 2019-03-05 20:00:01 UTC 14min left Mon 2019-03-04 20:00:01 UTC 23h ago systemd-tmpfiles-clean.timer systemd-tmpfiles-clean.service Wed 2019-03-06 00:30:00 UTC 4h 44min left n/a n/a your-service.timer your-service.service n/a n/a n/a n/a systemd-readahead-done.timer systemd-readahead-done.service