Re-starting Raspberry Pi Web Server on Reboot

Mechatronics, Software Engineering, Woodworking, and "Making" in General

Re-starting Raspberry Pi Web Server on Reboot

Recently, I’ve put together a home automation tool that uses a Flask project to control the state of the RPi’s GPIO pins. As an example, the pin state is driving a relay to control gas fireplace, decorative LEDs, etc.

For the tool’s general “healthy state”, the web server from Flask needs to be running on a predefined port. In the event the Raspberry Pi loses power, there should be a mechanism to restart the server.

If you want to run a specific python command when your raspberry pi is powered on, you can use a simple method called cron. Cron is a tool that allows you to schedule tasks to run at specific times or intervals. For example, you can use cron to start a web server every time your raspberry pi boots up.

To use cron, you need to edit a file called crontab, which contains the list of commands and the times when they should run. You can edit the crontab file using the following command in the terminal:

`crontab -e`

This will open the crontab file in a text editor. You can then add a line at the end of the file with the following format:

`@reboot python /path/to/your/script.py`

The `@reboot` keyword tells cron to run the command when the system boots up. The `python` command tells cron to use the python interpreter to execute your script. The `/path/to/your/script.py` is the location of your python script that contains the code you want to run. For example, if you want to start a web server using Flask, your script might look something like this:

You can save this script as `webserver.py` in your home directory, and then add the following line to your crontab file:

`@reboot python /home/pi/webserver.py`

After saving and exiting the crontab file, you can reboot your raspberry pi and check if your web server is running by visiting http://raspberrypi.local/ in your browser. You should see a message saying “Hello, World!”.

That’s it! You have successfully learned how to run a specific python command when your raspberry pi is powered on. You can use this method to run any python script or command that you want. You can also use other keywords besides `@reboot` to schedule tasks at different times or intervals. For more information about cron and its syntax, you can check out this tutorial: https://www.raspberrypi.org/documentation/linux/usage/cron.md

Another helpful resource is this here: Crontab Reboot: Execute a Job Automatically at Boot | phoenixNAP, also giving examples for how to call function on delay after reboot.