Systemd Timers
One way to schedule jobs on a Linux system is to use a timer file for systemd. This provides additional logging that you wouldn’t normally get with crontab. This page will go through a general setup. We will be using a oneshot service to be scheduled.
Script
This script will be what gets executed on a timer. We will make a test script for this. Copy the following data to /usr/local/bin/techjourney
:
#!/bin/bash
date
Then set the permissions to 755
so that it can be executed.
Service
The service file will be what gets called by our timer. Use the following values and add it to /etc/systemd/system/techjourney.service
:
[Unit]
Description=techjourney test service
[Service]
Type=oneshot
ExecStart=/usr/local/bin/techjourney
[Install]
WantedBy=multi-user.target
Timer
The timer file needs to have the same service name as our service file. Ours will be called techjourney.timer
and place it at /etc/systemd/system/
:
[Unit]
Description=techjourney timer
[Timer]
OnCalendar=*-*-* *:*:0/5
AccuracySec=1s
[Install]
WantedBy=timers.target
The OnCalendar field is of the format: Y-m-d H:M:S. the 0/5
above means every 5 seconds it will run the corresponding service.
Start Timer
For our test we will start the timer manually. First we need to reload the daemon.
sudo systemctl daemon-reload
Now start the timer.
sudo systemctl start techjourney.timer
Validation
To validate check the journal.
journalctl
You should see the dates being generated in the journal every 5 seconds. You can enable timers as well to ensure it starts at boot.