Running Python process with cronjob and checking it is still running every minute

Viewed 5012

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.

Cronjob is:

/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.

4 Answers

In your crontab file, have this code:

command='/usr/bin/python2.7 /home/mydir/public_html/myotherdir/script.py'

\* * * * * pgrep -af "$command" || $command

Explanation: Every minute, pgrep checks whether the python script is already running. If it is running, the 2nd statement will not be called since we used ||. If pgrep fails to find the python script in the existing processes, the 2nd statement will be executed and the python script will be back on work

Related