I run all my Raspberry Pi’s headless, connected to my Wi-Fi. This means I need that Wi-Fi connection to be able to do anything with that Raspberry Pi. I noticed that every once in a while, my Raspberry Pi would lose its Wi-Fi connection. I could try to find out why that is, but as a quick fix, it is easier to just have the Raspberry Pi restart if the Wi-Fi connection is lost, as a restart usually fixes the problem.
What we will need for this is something that tests my connection periodically (like once every 5 minutes), and if it cannot connect, restart the Raspberry Pi. On restart, the script needs to work again.
I used to have a solution with a Python script, called by a bash script, started by a cron job. It worked, but that did feel quite convoluted. When I was setting up a new Raspberry Pi I found a more elegant solution using Watchdog.
Before we start, make sure our Raspberry Pi is up to date:
sudo apt update sudo apt upgrade -y
Then use the instructions provided by DEFGW on his blog to set up Watchdog to monitor the connection and reboot if the connection is lost.