Tim Linden

I'm the CTO of TimTech, I love coding with PHP and MySQL.
I'm addicted to tracking clicks and email marketing.

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.

Select Code
define('PIDFILE', '/home/username/public_html/file.pid');

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

file_put_contents(PIDFILE, posix_getpid());
function removePidFile() {

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!

2 Kudos

2 comments for “How to prevent a PHP script from running while it’s still running

  1. December 3, 2013 at 2:52 pm

    Pretty geeky, Tim. But as a webmaster myself, I like reading up on this sort of stuff. Keep it coming. :)

  2. December 3, 2013 at 8:38 pm

    It’s pretty simple alright! LOL! This stuff pretty much goes over my head. I’m impressed with your programming talents, Tim!

Comments are closed.

%d bloggers like this: