pythoncronreboot

Autostarting Python scripts on boot using crontab on rasbian


I am a pretty new python programmer and am a little bit familiar with crontab. What I am trying to do is probably not the best practice but it is what I am most familiar with.

I have a raspberry pi with a couple python scripts I want to run on boot and stay running in the background. They are infinite loop programs. They are tested and working in a cmd terminal and have been function for a couple weeks. Just getting tired on manually starting them up. When the pi goes through a power cycle.

So I did a sudo crontab -e and added this line as my only entry

@reboot /usr/bin/python3 /usr/bin/script.py &

If I copy paste this exactly (minus the @reboot) it will run successfully in the cmd line.

I am using a cmd: pgrep -af pythonto check to see if it is running. I normally see two scripts running there but not the one I am trying to add.

I am not sure where I am going wrong or my best method to troubleshoot my issue. From the research I have been doing it seems like it should work.

Thanks for your help Kevin


Solution

  • You might find it easier to create a systemd service file for each program that you want to start when you Raspberry Pi boots. systemd comes with a few more tools to help you debug your configuration.

    This is what an example systemd service file (located at /etc/systemd/system/myscript.service) would look like:

    [Unit]
    Description=My service
    After=network.target
    
    [Service]
    ExecStart=/usr/bin/python3 /usr/bin/script.py
    WorkingDirectory=/home/pi/myscript
    StandardOutput=inherit
    StandardError=inherit
    Restart=always
    User=pi
    
    [Install]
    WantedBy=multi-user.target
    
    

    and then you can enable this program to run on boot with the command:

    sudo systemctl enable myscript.service
    

    These examples are from Raspberry Pi's documentation about systemd. But because systemd is widely used in the Linux world, so you can also follow documentation and StackOverflow answers for other Linux distributions.