Check for process already running in webfaction

cronprocess

I use Django framework on webfaction and have 5 different cron jobs. One of them lasts much longer than others and sometimes gets stuck (30-120 seconds or more).

I have already set that cron job to run every other minute, however, If is isn't completed, another process with /home/aemdy/webapps/hvan/myproject/myfile.py starts that causes high memory usage, slow site work and leads to apache crash or memory leak.

I don't want to set it to */3 * * * *, however, I want something like:

if this process in process list:
    pass
else:
    run process

Can this be done?

Best Answer

The traditional method to accomplish this would be to have your script check for existence of a file in /var/run when it starts, if none exists then create one containing its own PID. On completion, the script would remove this file. If the file does exist, the script simply exits. In this way, regardless of how frequently the script is called it will only execute its main code if it is not already running.

The problem with this approach is that an unclean termination leaves this file present on the system, so it is often augmented with a check to see if the specified PID exists and whether that PID is for the correct script.

This method does require that you change your script rather than simply amending your crontab entry, but is a time-honoured mechanism for solving this kind of problem.

Related Question