How to prevent a PHP script from running while it’s still running

When you’re running cron jobs sometimes you’ll need to run things that use a lot of CPU or other resources. If you need it to run right away, but you don’t want to copies running at the same time, it’s pretty simple to setup.

The way I’ve been doing it is by creating a file at the top of the script, and deleting it at the end. When the script starts you just check if the file is there, and if it is, you quit.

[code]define(‘PIDFILE’, ‘/home/username/public_html/file.pid’);

if (file_exists(PIDFILE)) { EXIT(); }

file_put_contents(PIDFILE, posix_getpid());
function removePidFile() {
unlink(PIDFILE);
}
register_shutdown_function(‘removePidFile’);[/code]

What I’ve done is used the register_shutdown_function so that way it deletes it on exit. The benefit is you don’t have to mess with all your code to ensure every area it could possibly stop running deletes the file.

Then I simply set the cron job to run every minute. It will check if there is something to do, if there isn’t, it exits, if there is it keeps going and no new jobs start till it’s finished. Real simple!

6 thoughts to “How to prevent a PHP script from running while it’s still running”

Leave a Reply

Your email address will not be published. Required fields are marked *