From cron to systemd timers

Written by

in

You may have come across new Linux distributions don’t include cron. As they use systemd, they are encouraging you to use systemd’s timers instead.

cron was simple to use

crontab -e and enter the commands you need.
Yes, there is the awkward syntax to say exactly when to run it, but, like me, you probably have something like this that you put at the top of your crontab:

# mm hh dd MM dow
#  |  |  |  |   \--day of week (0=sun, etc.)
#  |  |  |  \------month (1-12 or jan/feb etc.)
#  |  |  \---------date (1-31)
#  |  \------------hour (0-23)
#  \---------------minute (0-59) [*/5 = every 5 mins]
  30 04  *  *  1 /home/user/script 

What follows is the systemd way of doing the same thing:
at 4:30am every Monday, run /home/user/script

Systemd timers

Systemd timers aren’t hard to use, but the setup is different.
You create /etc/systemd/system/mytask.timer

[Unit]
Description=this template runs every Monday at 4:30am

[Timer]
OnCalendar=Mon 04:30
Unit=mytask.service

[Install]
WantedBy=timers.target

and you create /etc/systemd/system/mytask.service

[Unit]
Description=this task does something

[Service]
ExecStart=/home/user/script

Once created, check the syntax (and fix any errors)

systemd-analyse verify /etc/systemd/system/mytask.*

Then you can start the timer

systemctl enable mytask.timer
systemctl start mytask.timer

and you can check everything is working with

systemctl list-timers

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *