PHP - Using File Locks to Prevent Duplicate Process

The script below provides a function which allows the developer to prevent duplicates of the same PHP process running. This is useful if you are automatically calling a script from a cron job, but the execution time cannot be determined or may vary. This is very similar to the one I wrote for Java

Please note that in this example, the script will immediately halt in the event of a duplicate, but you can change the behaviour, making the duplicate script wait (block) until the former is finished, instead of halting, by removing the 'LOCK_NB |' mask. However, this may be dangerous as your script calls could stack up.

Strictly speaking, it's usually best to check your processes to ensure that duplicate processes aren't going to be run, but I found that the use of file locking to be a very quick and easy instead. Please note that I am not sure if this will work on Windows, but aimed and Unix systems. Also, this is only good for preventing a process from running if a single instance is already running, e.g. it wont allow you to keep a pool of 2+ processes running unless you add more file locks).

Why Store Hndle in Global Variable?

Eagle-eye developers may notice that I am storing the file handle in a global variable and then doing nothing with it. You may believe that this is a waste, but it's not. PHP is quite intelligent and would release the file lock as soon as the reference to the handle is lost, so I hold it in a global variable to prevent this. You don't have to use it again, just leave it in memory.

No comments:

Post a Comment