natbox.io

Guides / Scheduled tasks

Run scheduled tasks with systemd timers

About 5 minutes. Debian, Ubuntu and AlmaLinux. Good for reports, scrapers, clean-ups and backups.

Timers do the same job as cron, but they keep logs and can catch up on a run missed while the server was off.

1. Create your script

Save as /usr/local/bin/hello.sh:

#!/bin/sh
date >> /var/log/hello.log
chmod +x /usr/local/bin/hello.sh

2. Describe the job

Save as /etc/systemd/system/hello.service:

[Unit]
Description=Hello job

[Service]
Type=oneshot
ExecStart=/usr/local/bin/hello.sh

3. Set the schedule

Save as /etc/systemd/system/hello.timer. This runs every 5 minutes:

[Unit]
Description=Run hello every 5 minutes

[Timer]
OnCalendar=*:0/5
Persistent=true

[Install]
WantedBy=timers.target
systemctl daemon-reload
systemctl enable --now hello.timer

4. Check it

systemctl list-timers hello.timer   # when it runs next
systemctl start hello               # run it now
journalctl -u hello                 # see its logs

Other schedules

OnCalendar=hourly
OnCalendar=daily
OnCalendar=*-*-* 03:30:00     # every day at 03:30
OnCalendar=Mon *-*-* 09:00:00 # Mondays at 09:00

Server times are in UTC unless you change the time zone. Change a schedule, then run systemctl daemon-reload and systemctl restart hello.timer.