How to restart a SystemD service weekly using SystemD timers

The following example restarts a service every week on Sunday at 06:00 using SystemD timers.

The easiest way to use this is to use the autoinstall script below, which creates the necessary files and enables the timer. If you want to create it manually, copy the .timer and .service files to /etc/systemd/system/, reload systemd using systemctl daemon-reload and enable and start the timer using systemctl enable --now myservice-restart.timer.

Don’t forget to replace myservice with the actual name of your service in all files!

Service file example

myservice-restart.service
[Unit]
Description=Restart myservice

[Service]
Type=oneshot
ExecStart=/bin/systemctl restart myservice

Timer file example

myservice-restart.timer
[Unit]
Description=Restart myservice every Sunday at 06:00

[Timer]
OnCalendar=Sun *-*-* 06:00:00  # No inline comments allowed here!
Persistent=true

[Install]
WantedBy=timers.target

Autoinstall script

install-weekly-autorestart.sh
#!/bin/bash

# TODO Define service name here
SERVICE_NAME="myservice"
# Optional configuation
TIMER_NAME="${SERVICE_NAME}-restart"
SERVICE_FILE="/etc/systemd/system/${SERVICE_NAME}.service"
TIMER_FILE="/etc/systemd/system/${TIMER_NAME}.timer"
SERVICE_RESTART_FILE="/etc/systemd/system/${TIMER_NAME}.service"

# Check if the script is run as root
if [ "$(id -u)" -ne 0 ]; then
    echo "Error: This script must be run as root (use sudo)." >&2
    exit 1
fi

# Check if the target service exists
if [ ! -f "$SERVICE_FILE" ]; then
    echo "Error: Service file '$SERVICE_FILE' does not exist. Create it first." >&2
    exit 1
fi

# Create the timer service file (oneshot to restart the target service)
cat > "$SERVICE_RESTART_FILE" <<EOF
[Unit]
Description=Restart $SERVICE_NAME

[Service]
Type=oneshot
ExecStart=/bin/systemctl restart $SERVICE_NAME
EOF

# Create the timer file (no inline comments in OnCalendar!)
cat > "$TIMER_FILE" <<EOF
[Unit]
Description=Restart $SERVICE_NAME every Sunday at 06:00

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

[Install]
WantedBy=timers.target
EOF

# Reload systemd, enable, and start the timer
echo "Reloading systemd..."
systemctl daemon-reload

echo "Enabling and starting the timer..."
systemctl enable --now "$TIMER_NAME.timer"

# Verify the timer is active
echo "Verifying timer status..."
systemctl list-timers --all | grep "$TIMER_NAME"

echo "Installation complete!"
echo "The service '$SERVICE_NAME' will now restart every Sunday at 06:00."

Check out similar posts by category: Systemd, Linux