Sunday, June 15, 2014

Replacing crontab with systemd timers

As of systemd version 212, you can use timers to schedule regular jobs. Systemd timers offer more functionality compared to crontab. See systemd.time for more details.

This post will show how to create timer job for ownclouds' cron.php job.

Basically, you need to create 2 files:
  • systemd .service file
  • systemd .timer file
Place these files in /etc/systemd/system.

cron-owncloud@http.service:
-this file will execute specified command. Notice the @http which ensures that the command will be executed with user http.

cat /etc/systemd/system/cron-owncloud\@http.service 
[Unit]
Description=owncloud cron job
Wants=cron-owncloud.timer

[Service]
User=%I      # comment this line if you want to run as root
Type=oneshot
Nice=19
IOSchedulingClass=2
IOSchedulingPriority=7
ExecStart=/usr/bin/php -f /srv/http/owncloud/cron.php 1>/dev/null

[Install]
WantedBy=basic.target

cron-owncloud.timer:
-this file will trigger .service file at specified time (OnCalendar). In this case, the service will be trigged each 5 minutes, in 20th second.

cat /etc/systemd/system/cron-owncloud.timer
[Unit]
Description=owncloud cron.php job

[Timer]
# To add a time of your choosing here, please refer to systemd.time manual page for the correct format
OnCalendar=*-*-* *:0/5:20
Persistent=true
Unit=cron-owncloud@http.service

[Install]
WantedBy=basic.target
Now you can enable and start this timer:
systemctl daemon-reload
systemctl enable cron-owncloud.timer
systemctl start cron-owncloud.timer

8 comments:

  1. Hi, I thing I had a problem when the user was set directly, the job ran always under root... but I'm not sure, it was a while ago...
    There is one upside thought, you can directly see which user runs which job just by listing the directory :)

    ReplyDelete
  2. Thanks for your fast reply. Keep up the work on the great articles including snippets on your blog!

    ReplyDelete
  3. Replies
    1. Hi, the whole point was in elimination of old cron way and to try out something new.
      systemd timer also offers more options and complex configuration for jobs execution.

      Delete
  4. The line:
    User=%I # comment this line if you want to run as root

    was giving me:
    Failed at step USER spawning /usr/bin/php: No such process

    Oddly enough, just removing the comment fixed the problem... I don't know why :<

    ReplyDelete
  5. Hi, the type of service should be oneshot, not simple. Otherwise this service consistently shows up as failed.

    ReplyDelete
  6. Thanks for sharing such a valuable information.This post is very useful for me.Jobs in PHP

    ReplyDelete