Creating an Automated Script That Runs Every Midnight! ~ Migrating from crontab to systemd Timer ~

This time, we will explain how to migrate from using crontab to systemd Timer, based on the crontab script we used for updating Let’s Encrypt certificates!


目次

The Objective

We want to run a script every day at midnight (00:00) to renew our SSL certificate!
Originally, it was running with the following crontab configuration:

0 0 * * * bash /tmp/letsencrypt.sh

We will change this configuration to systemd Timer to enable more flexible and convenient management.


Procedure: Setting up using a Timer

Creating the Service File

First, create a “service file" to execute the script. Save the following content with the name /etc/systemd/system/letsencrypt-renew.service.

[Unit]
Description=Run Let's Encrypt renewal script
Wants=letsencrypt-renew.timer

[Service]
Type=oneshot
ExecStart=/bin/bash /tmp/letsencrypt.sh

[Install]
WantedBy=multi-user.target

Creating the Timer File

Next, create a “timer file" that defines the execution schedule. Write the following content to /etc/systemd/system/letsencrypt-renew.timer.

[Unit]
Description=Run Let's Encrypt renewal script daily at midnight

[Timer]
OnCalendar=*-*-* 00:00:00
Persistent=true

[Install]
WantedBy=timers.target

Here, OnCalendar=*-*-* 00:00:00 specifies execution at “midnight every day."

Applying the Settings and Enabling the Timer

Run the following commands in order to apply the configuration.

sudo systemctl daemon-reload
sudo systemctl enable letsencrypt-renew.timer
sudo systemctl start letsencrypt-renew.timer

To verify that the settings have been applied correctly, run the following:

sudo systemctl list-timers --all

Complete!

Now, the Let’s Encrypt certificate renewal script will automatically run every day at midnight! Using systemd Timer is very convenient because it makes retrying after failures and checking logs much easier.