Steps to get systemd timers working as a replacement for a cron job.
To run a timer at the user level (eg. without root access) create the directory $HOME/.config/systemd/user
:
mkdir -p ${HOME}/.config/systemd/user
Create the service file for the command that should be ran. For this example the file will run the Wordpress cron, the service file will be created as $HOME/.config/systemd/user/wordpress.service
.
[Unit]
Description=Run WordPress cron
After=network.target
[Service]
Type=simple
WorkingDirectory=/home/mywebsite/public_html
ExecStart=/usr/bin/php /home/mywebsite/public_html/wp-cron.php
[Install]
WantedBy=default.target
The timer file can then be created, it should have the same file name as the service except instead of the extension service
it should be timer
(so in this case $HOME/.config/systemd/user/wordpress.timer
):
[Unit]
Description=Run WordPress cron
After=network.target
[Timer]
Persistent=false
OnCalendar=minutely
Unit=wp-cron.service
[Install]
WantedBy=timers.target
Process lingering will need to be enabled if the timer is to be running without the user being logged in:
sudo loginctl enable-linger $USER
Enable and start the timer:
systemctl --user enable wordpress.timer
systemctl --user start wordpress.timer
The timer can be monitored (eg. to see when it will next run) by using the status
systemctl command:
systemctl status wordpress.timer
System level timers are created the same way just stored in the path /etc/systemd/system
.
The OnCalendar
option sets the date and time that the timer should be executed. The systemd.timer manual page has instructions for formatting.
To validate, you can use systemd-analyze calendar
:
systemd-analyze calendar --iterations=5 '*-*-13,28 08:25:00'
The --interactions
argument specifies a number of next dates/times that would match:
~ $ systemd-analyze calendar --iterations=5 '*-*-13,28 08:25:00'
Normalized form: *-*-13,28 08:25:00
Next elapse: Fri 2023-04-28 08:25:00 AWST
(in UTC): Fri 2023-04-28 00:25:00 UTC
From now: 1 week 6 days left
Iter. #2: Sat 2023-05-13 08:25:00 AWST
(in UTC): Sat 2023-05-13 00:25:00 UTC
From now: 4 weeks 0 days left
Iter. #3: Sun 2023-05-28 08:25:00 AWST
(in UTC): Sun 2023-05-28 00:25:00 UTC
From now: 1 month 12 days left
Iter. #4: Tue 2023-06-13 08:25:00 AWST
(in UTC): Tue 2023-06-13 00:25:00 UTC
From now: 1 month 28 days left
Iter. #5: Wed 2023-06-28 08:25:00 AWST
(in UTC): Wed 2023-06-28 00:25:00 UTC
From now: 2 months 13 days left