It’s about time – how to auto-run your Python scripts on Raspberry Pi OS with Cron jobs

This is a step by step reminder how to get your Python scripts run automatically on your Raspberry. We will be creating a cron job that is run once when booting. (This should be possible like this or pretty similar on every Linux distribution where Cron is available and is not limited to Python scripts of course.)

open crontab for the current user, which will most probably be “pi”

Open the console and type: crontab -e
As this is probably the first time you open up the cron tab you will be asked which editor to use. As nano is pointed out to be the easiest I chose 1.

crontab for the current user

You opened the crontab. Congratulations 😉 Have a look at the documentation and continue by scrolling down / moving your cursor down to the bottom of the file.

cron job which is run once when booting

As the script runs in an endless loop it has only to be run once when booting. For that we don’t have to enter a specific time or interval, but only @reboot. Because it runs endlessly we have to add & at the end. python3 is the command I want to run with the file location of my script as parameter.

@reboot python3 /home/pi/my_script.py &

Next and last step is to save the new cron job. For that press [CTRL] + [X] to exit – you will be asked if you want to save the changes -> [Y]. Press enter to confirm the file save.

You’re all set. Reboot your Raspberry and your script will be run.

https://en.wikipedia.org/wiki/Cron

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.