Run Program at Boot using Cron

Jan 2017

Introduction

I was using the .bashrc file when logged in as a user (from your home directory, type sudo nano .bashrc) to launch scripts upon the Raspberry Pi bootup. However, while this works, its has one really annoying issue. If you login from another place, say from SSH, then the script runs again, which isn't great for my application.
So I am now using Cron, which works as I expect, Cron starts the script at boot, and I can login from anywhere without fear of the script running again.
Cron (short for the greek word for time - Chronos) is a scheduling utility that can run tasks on a time base of minutes, hours, days etc. (great for making automatic weekly backups). But Cron can also run tasks at boot, which is the part we are going to use.
To avoid putting loads of commands in to Cron, its best to group them all in to a file, then just reference that file in Cron. For this example we will make a file called launcher.sh.

Create Launcher Script

To create our launcher script, first ensure you are in a directory you have rights to, on the Raspberry Pi this will generally be the Pi location in the Home folder.

cd /home/pi

Now enter the following:

sudo nano launcher.sh

Paste this code in to the launcher.sh file you have open.

#!/bin/sh
# launcher.sh
# navigate to home directory, then to this directory, then execute python script.
cd /
cd home/pi
sudo python nameOfScriptorProgram &

Be sure to replace the part nameOfScriptorProgram with the name of your script or program.
Save the file by using Ctrl-X and answering Yes.

Execution Rights

The script will not run unless it is made executable. to do this enter the following:

sudo chmod 755 launcher.sh

Testing the Launcher.sh

Before adding as a Cron job, it is a good idea to test the script, to do this enter:

./launcher.sh

Your script/program should now run. If it does then you can move on to the Cron part.