Rich0's Gentoo Blog

Archive for July 2015

Running cron jobs as units automatically

with 9 comments

I just added sys-process/systemd-cron to the Gentoo repository.  Until now I’ve been running it from my overlay and getting it into the tree was overdue.  I’ve found it to be an incredibly useful tool.

All it does is install a set of unit files and a crontab generator.  The unit files (best used by starting/enabling cron.target) will run jobs from /etc/cron.* at the appropriate times.  The generator can parse /etc/crontab and create timer units for every line dynamically.

Note that the default Gentoo install runs the /etc/cron.* jobs from /etc/crontab, so if you aren’t careful you might end up running them twice.  The simplest solutions this are to either remove those lines from /etc/crontab, or install systemd-cron using USE=etc-crontab-systemd which will have the generator ignore /etc/crontab and instead look for /etc/crontab-systemd where you can install jobs you’d like to run using systemd.

The generator works like you’d expect it to – if you edit the crontab file the units will automatically be created/destroyed dynamically.

One warning about timer units compared to cron jobs is that the jobs are run as services, which means that when the main process dies all its children will be killed.  If you have anything in /etc/cron.* which forks you’ll need to have the main script wait at the end.

On the topic of race conditions, each cron.* directory and each /etc/crontab line will create a separate unit.  Those units will all run in parallel (to the extent that one is still running when the next starts), but within a cron.* directory the scripts will run in series.  That may be a bit different from some cron implementations which may limit the number of simultaneous jobs globally.

All the usual timer unit logic applies.  stdout goes to the journal, systemctl list-timers shows what is scheduled, etc.

Written by rich0

July 18, 2015 at 12:00 pm

Posted in gentoo, linux, systemd