Systemd – Schedule Your Tasks With Timers

You created your own systemd unit files.
If you missed the article, you find it here.

Now you learn to run it on a schedule – instead of starting it manually.

The systemd timer way.

A systemd timer does not perform the task itself.

It activates a service.

  • The service defines what should happen.
  • The timer defines when it should happen.

The Systemd Unit File

You have a simple service.
It does not have to run as a daemon.

Imagine a backup script.

The unit file looks like this:

[Unit]
Description=Create a system backup
[Service]
Type=oneshot
ExecStart=/usr/local/bin/system-backup.sh

The service type is oneshot.
It runs the command and exits.
It does not need to run continuously.

The timer will start the service according to its schedule.

After creating or changing a unit file, tell systemd to reload its unit files:

sudo systemctl daemon-reload

The service is defined in the /etc/systemd/system/system-backup.service unit file.

You can trigger a manual run of the service:

sudo systemctl start system-backup.service

Or you create a systemd timer to run it on a schedule.

The Systemd Timer

Add a new file – /etc/systemd/system/system-backup.timer.

The timer has three sections.

The [Unit] section describes the timer.

The [Timer] section contains the schedule.

The [Install] section determines how the timer is enabled.

The system-backup timer should look like this:

[Unit]
Description=Run system backup daily
[Timer]
OnCalendar=daily
[Install]
WantedBy=timers.target

From now on, you start the timer instead of starting the service manually.

The timer will activate the service according to its schedule.

system-backup.timer
│
│ activates
▼
system-backup.service

You activate the timer with:

sudo systemctl daemon-reload
sudo systemctl enable --now system-backup.timer

The enable command makes the timer start automatically when the system boots.

The --now option starts the timer immediately as well.

Now the files are:

/etc/systemd/system/
├── system-backup.service
└── system-backup.timer

The schedule can be configured precisely, for example:

OnCalendar=*-*-* 03:00:00

More information can be found on the systemd.timer manual page.

Check The Timers

You can list the timers:

sudo systemctl list-timers

Check a specific timer:

sudo systemctl list-timers system-backup.timer

Final Thoughts

Systemd provides an integrated system for managing the scheduling.
The configuration of units and timers live in the same directory.
The format is similar.

If you already know cron, think of a systemd timer as the scheduling mechanism –
but remember that systemd separates the schedule from the task itself.


Discover more from Tom's IT Cafe

Subscribe to get the latest posts sent to your email.

Leave a signal

Discover more from Tom's IT Cafe

Subscribe now to keep reading and get access to the full archive.

Continue reading