Tuesday, July 26, 2022

[SOLVED] RPi 4 - cant get cron job to work (Python, virtual env)

Issue

Trying to run a cron job on a RPi 4. It should execute a Python script with a virtual env. I have tried all the common solutions that I found, but it doesn't work. I have very little knowledge of Linux. My Pi should have a default setup (I did not change much).

What I tried:

#1 07 11 * * * cd /home/pi/Scripts/Retail-Folders && /home/pi/Scripts/Retail-Folders/folders_venv/bin/python /home/pi/Scripts/Retail-Folders/main.py

#2

SHELL=/bin/bash
07 11 * * * cd /home/pi/Scripts/Retail-Folders && /home/pi/Scripts/Retail-Folders/folders_venv/bin/python /home/pi/Scripts/Retail-Folders/main.py

#3 07 11 * * * cd /home/pi/Scripts/Retail-Folders && . /home/pi/Scripts/Retail-Folders/folders_venv/bin/activate /home/pi/Scripts/Retail-Folders/main.py

I don't believe this should be that hard. Any help is greatly appreciated.

Edit: by the way, the python file is made executable.


Solution

Okay so in the end I figured out what went wrong. It concerns a script that runs Selenium and my RPi is not attached to a monitor. Apparently that does not work with cron until you specify 'DISPLAY=:0'. This was the solution for me.

Even though I greatly appreciate the answer by criztovyl, I feel like I should mark this as the solution as it explains my original issue. Please correct me if this is not according to convention.

Final crontab to make it work:

SHELL=/bin/bash
DISPLAY=:0
40 15 * * * cd /path/to/folder && /path/to/venv/bin/python main.py >> /path/to/logfile.txt 2>&1


Answered By - repjas
Answer Checked By - Terry (WPSolving Volunteer)