Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 628
the_t_test_1 Avatar asked Aug 15 '17 23:08

the_t_test_1


1 Answers

There is now a better way to do this via utility called flock, directly from cron task within a single line. flock will acquire a lock before it runs your app and release it after it is run. The format is as follows:

* * * * * /usr/bin/flock -n /tmp/fcj.lockfile <your cron job>

For your case, this'd be:

* * * * * /usr/bin/flock -n /tmp/fcj.lockfile /usr/bin/python2.7 /home/mydir/public_html/myotherdir/script.py

-n tells it to fail immediately if it cannot acquire the lock. There is also -w <seconds> option, it will fail if it cannot acquire the lock within given time frame.

 * * * * /usr/bin/flock -w <seconds> /tmp/fcj.lockfile <your cron job>
like image 116
Caner Avatar answered Nov 02 '22 20:11

Caner