Drupal Cron Job with Systemd

EDIT: The first version of this post had no failure handling. So I’ve changed the curl arguments after reading a comment on drupal.org and then I wrote another article handling unit failure in systemd.

##Intro

So I have just setup Drupal for the first time in years (tried it out back in 2005-2006 something but never really used it).

While setting up Drupal I ran into a problem, the manual about “configuring cron jobs” did not cover how to setup Drupals Cron task if you use Systemd and Googling for it did not (at the time) give any concrete answers. So I compiled the results I got into my own solution.

##Solution

To setup a cron task, or Timer as it is called in systemd requires two parts, first a Service that will do the actual work, and a Timer that will invoke the Service at the specific interval (or date, or whatnot). Both the Timer and Service are going to share the same name (but with different file prefixes “.service” and “.timer”), I used the name “nllabs-drupal-cron” but you can pick what you think is logical for your setup.

###Step 1

First part, the service, you will need to insert your own address instead of example.com and insert your own cron_key (which you can find under: admin/reports/status):

“/etc/systemd/system/sitename-drupal-cron.service”

[Unit]
Description=Drupal Cron Service
After=network.target

[Service]
Type=simple
ExecStart=/usr/bin/curl -f -sS http://example.com/cron.php?cron_key=xxxxxxxx
User=nobody
Group=nobody

###Step 2 The second step, the timer: “/etc/systemd/system/sitename-drupal-cron.timer”

[Unit]
Description=Drupal Cron Timer

[Timer]
OnBootSec=10min
OnUnitActiveSec=45min

[Install]
WantedBy=multi-user.target

This timer will invoke the service defined earlier every 45 minutes starting from 10 min after boot.

###Testing

To test the service you can execute the command:

systemctl start sitename-drupal-cron.service

###Enable the timer

To start and enable the timer use the commands:

systemctl start sitename-drupal-cron.timer
systemctl enable sitename-drupal-cron.timer

###Handling faults

The solution presented here does not notify the administrator in case the cron job fails, I’ve written another article about sending mail when a unit fails in systemd.

Further reading material: