Using Cron Job To Check If Python Script Is Running
Solution 1:
I think it would be better if you made your webserver write its process id into a file and then have you cron job read that and check if the process is running.
It would also be useful to use some kind of framework that does process management (e.g. supervisord, upstart etc.) rather than manually launch it using os.system
.
Solution 2:
I like to do this with a shell script similar to the following. It is simple and has low likelihood of errors. Generally I put this in a while loop with sleep at the end, but cron works fine too.
if [ -x myproc.pid ] ; then
pid=`cat myproc.pid`
else
pid=1
fikill -0 $pid#check if process is still running
As you can see it requires your process to write its PID into a file when it starts up. This avoids problems with grepping ps output because it can be tricky to get a regular expression that always works no matter what new process names come onto your server in future. The PID file is dead certain.
kill -0
is a little known way of checking if a process is running and is simpler than checking for a directory in /proc
. The line with pid=1
is there because the checker is not root therefore the kill check will always fail if you can't send signals to the process. That is there to cover the first time that myproc is run on this server. Note that this means that the checking script must not run as root
(generally good practice) but must run as the same user which runs the process you are checking.
If you really want to do this in Python, then the os
module has access to PIDs and has a kill
method. However it doesn't return a shell exitcode, instead os.kill
throws OSError
exceptions which you can handle in a try
- catch
block. The same principle applies of using signal 0 to detect whether the process exists or not but there is a slim chance that your process has died and another process now has the same pid, so do handle that case in your try
- catch
.
Solution 3:
You could probably do it by starting the application in the background and possibly making it immune to hang up signals.
Try changing the system command to:
nohup python webserver.py &
Post a Comment for "Using Cron Job To Check If Python Script Is Running"