Running a Service at Fixed Intervals on Debian

There are many ways to run a service at fixed intervals on Debian, such as: cron, anacron, systemd timers, at, and sleep loop.

1. Create the script (if it doesn’t exist)

Make sure you have your script ready. For example, wg-auto-reconnect.sh as shown at the end of this article:

sudo nano /usr/local/bin/wg-auto-reconnect.sh

Paste the script content and grant it execute permissions:

sudo chmod +x /usr/local/bin/wg-auto-reconnect.sh

2. Create a Systemd Service

Create a systemd service file for the script.

sudo nano /etc/systemd/system/wg-auto-reconnect.service

Paste the following content:

[Unit]
Description=Auto reconnect WireGuard if no internet connection

[Service]
Type=simple
ExecStart=/usr/local/bin/wg-auto-reconnect.sh

3. Create a Systemd Timer

Now, create a systemd timer file to activate the service at the desired interval.

sudo nano /etc/systemd/system/wg-auto-reconnect.timer

Add the following content:

[Unit]
Description=Run WireGuard auto-reconnect script every 10 minutes

[Timer]
OnBootSec=3min          # run 3 minutes after system boot
OnUnitActiveSec=10min   # run every 10 minutes after the last execution

[Install]
WantedBy=timers.target

In this example:

  • OnBootSec=3min means the timer will run 3 minutes after the system boots.
  • OnUnitActiveSec=10min means the script will be run every 10 minutes after its last execution.

4. Enable and Start the Timer

Reload the systemd daemon to recognize the new service and timer:

sudo systemctl daemon-reload

Enable and start the timer:

sudo systemctl enable wg-auto-reconnect.timer
sudo systemctl start wg-auto-reconnect.timer

5. Check the Timer’s Status

To ensure the timer is working, you can check its status:

sudo systemctl status wg-auto-reconnect.timer

This command will show the last time the script ran and when it will run next.

6. Manual Activation

If you want to test the script immediately without waiting for the timer, you can activate the service manually:

sudo systemctl start wg-auto-reconnect.service

Script (wg-auto-reconnect.sh)

  • check_internet: This function uses the ping command to Google’s DNS server (8.8.8.8) to check if there is an active internet connection.
  • check_wireguard: This function checks if WireGuard (wg0) is active using systemctl.
  • If there is an internet connection and WireGuard is already running, the script will exit.
  • If WireGuard is not active but there is an internet connection, the script will start WireGuard.
  • If there is no internet connection, WireGuard will be turned off, the script will wait for 3 seconds, and then recheck the connection. If the internet is back, WireGuard will be turned on.
  • If no connection is found after the second check, the script will exit.

This script will ensure WireGuard is properly managed according to the internet connection status and service state.