Using Systemd Timers Instead of Cron Jobs on Linux

PowerADM.com / Linux / CentOS / Using Systemd Timers Instead of Cron Jobs on Linux

You can use systemd timers to replace cron jobs on modern Linux distros. This article shows you how to use, create, and configure systemd timer on Linux.

Cron jobs are easy to understand and manage since all system jobs are stored in a single crontab file. Systemd timers offer much more functionality and features than classical cron in Linux.

List all timers in Linux:

$ systemctl list-timers --all

Show only active (enabled) systemd timers:

$ systemctl list-timers

View detailed information about a specific timer:

$ systemctl status logrotate.timer

View enabled systemd timer units on Linux

Let’s create a simple timer that writes the current time to currentdata.log every 5 minutes.

First, create a service configuration (unit) file:

$ sudo mcedit /etc/systemd/system/curdat.service

[Unit]
Description=Write current data to log file
Wants= curdat.times
[Service]
Type=oneshot
ExecStart= /bin/bash -c 'echo $(date) >> /var/log/current-date.log'
[Install]
WantedBy=multi-user.target

Check that the systemd service is working properly:

$ sudo systemctl daemon-reload
$ sudo systemctl start curdat.service
$ systemctl status curdat.service

You can see the unit log:

$ journalctl -u curdat.service

Now we are going to create systemd timer to start this service on a regular basis (we are going to run it every 5 minutes):

$ sudo mcedit /etc/systemd/system/curdat.timer

[Unit]
Description=Write current data to log file every minute
Requires=curdat.service
[Timer]
Unit= curdat.service
OnCalendar=OnCalendar=*:0/5
[Install]
WantedBy=timers.target

Start the timer:

$ sudo systemctl daemon-reload
$ sudo systemctl start curdat.timer

Enable the systemd timer:

$ sudo systemctl enable mydf.timer

This timer starts curdat.service every 5 minutes, check the logs:

$ journalctl -u curdat.service
$ journalctl -u curdat.timer
A separate log is created for each of the systemd timers.

To disable and stop the timer:

$ sudo systemctl disable curdat.timer
$ sudo systemctl stop curdat.timer
Leave a Reply

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