Issue
I have a Python script that I'd like to run from a cronjob and then check every minute to see if it is still running and if not then start it again.
/usr/bin/python2.7 /home/mydir/public_html/myotherdir/script.py
there is some info on this but most answers don't really detail the full process clearly, e.g.:
Using cron job to check if python script is running
e.g. in that case, it doesn't state how to run the initial process and record the PID. It leaves me with a lot of questions unfortunately.
Therefore, could anyone give me a simple guide to how to do this?
e.g. full shell script required, what command to start the script, and so on.
Solution
It's not that hard. First set up the crontab
to run a checker every minute:
* * * * * /home/mydir/check_and_start_script.sh
Now in /home/mydir/check_and_start_script.sh
,
#!/bin/bash
pid_file='/home/mydir/script.pid'
if [ ! -s "$pid_file" ] || ! kill -0 $(cat $pid_file) > /dev/null 2>&1; then
echo $$ > "$pid_file"
exec /usr/bin/python2.7 /home/mydir/public_html/myotherdir/script.py
fi
This checks to see if there's a file with the process id of the last run of the script. If it's there, it reads the pid and checks if the process is still running. If not, then it puts the pid of the currently running shell in the file and executes the python script in the same process, terminating the shell. Otherwise it does nothing.
Don't forget to make the script executable
chmod 755 /home/mydir/check_and_start_script.sh
Answered By - Gene Answer Checked By - Marie Seifert (WPSolving Admin)