Como reiniciar um serviço SystemD semanalmente usando timers SystemD

O exemplo a seguir reinicia um serviço toda semana no domingo às 06:00 usando timers SystemD.

A maneira mais fácil de usar isso é usar o script de autoinstalação abaixo, que cria os arquivos necessários e ativa o timer. Se você quer criar manualmente, copie os arquivos .timer e .service para /etc/systemd/system/, recarregue o systemd usando systemctl daemon-reload e ative e inicie o timer usando systemctl enable --now myservice-restart.timer.

Não se esqueça de substituir myservice pelo nome real do seu serviço em todos os arquivos!

Exemplo de arquivo de serviço

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

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

Exemplo de arquivo de timer

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

Script de autoinstalação

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

# TODO Defina o nome do serviço aqui
SERVICE_NAME="myservice"
# Configuração opcional
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"

# Verifica se o script está sendo executado como root
if [ "$(id -u)" -ne 0 ]; then
    echo "Error: This script must be run as root (use sudo)." >&2
    exit 1
fi

# Verifica se o serviço alvo existe
if [ ! -f "$SERVICE_FILE" ]; then
    echo "Error: Service file '$SERVICE_FILE' does not exist. Create it first." >&2
    exit 1
fi

# Cria o arquivo de serviço do timer (oneshot para reiniciar o serviço alvo)
cat > "$SERVICE_RESTART_FILE" <<EOF
[Unit]
Description=Restart $SERVICE_NAME

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

# Cria o arquivo de timer (sem comentários inline no 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

# Recarrega o systemd, ativa e inicia o timer
echo "Reloading systemd..."
systemctl daemon-reload

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

# Verifica se o timer está ativo
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