Script in crontab only partially executed

Solution 1:

It might be cleaner to use pkill rather than pgrep but I don't think that's the problem.

I'm not sure from the information you supply precisely why your script isn't working as expected (it looks OK to me).

However I'm not sure using '&' in scripts called from cron commands is the right thing to do. My first alternative suggestion would be to use the fact that cron natively runs things in the background, and have a separate cron job per python script rather than doing it all at once.

If I understand correctly, the symptom is that the python programs crash completely rather than hanging, and on the assumption it would be preferable to keep then running if they are happy, you could use a start-if-not-running script (I use bash):

#!/bin/bash
value=$( ps -ef | grep -ic "$1" )
if [ $value -lt 2 ]
then
    python3 "$1"
fi

and then in your crontab:

15 * * * * bash /path/to/script/start-if-not-running.bash script1.py
30 * * * * bash /path/to/script/start-if-not-running.bash script2.py
45 * * * * bash /path/to/script/start-if-not-running.bash script3.py

Explanation:

ps -ef searches the entire command line of the process table (pgrep and pkill by default only search the first 13 characters)

$value -lt 2 means if there are less than two matches then go ahead and start a new script (there will always be one match - that of the grep command itself)

I'd also strongly recommend making sure your raspberry pi emails you the outputs from cron commands if you haven't got that set up already (e.g. https://medium.com/swlh/setting-up-gmail-and-other-email-on-a-raspberry-pi-6f7e3ad3d0e) as an aid to debugging.