How to detect whether a PHP script is already running?
✔ Recommended Answer
If you need it to be absolutely crash-proof, you should use semaphores, which are released automatically when php ends the specific request handling.
A simpler approach would be to create a DB record or a file at the beginning of the execution, and remove it at the end. You could always check the "age" of that record/file, and if it's older than say 3 times the normal script execution, suppose it crashed and remove it.
There's no "silver bullet", it just depends on your needs.
Source: stackoverflow.com
Answered By: MartinodF
One common way to detect whether a PHP script is already running is to use a lock file. A lock file is a file that is created when the script starts running, and is deleted when the script finishes. While the lock file exists, any subsequent attempts to run the script will detect its presence and exit gracefully.
Here's an example implementation of this approach:
php$lockFile = '/path/to/lockfile';
// Check if lock file exists
if (file_exists($lockFile)) {
// Lock file exists, script is already running
exit();
}
// Create lock file
touch($lockFile);
// Do some work
// Delete lock file
unlink($lockFile);
In this example, the script first checks if the lock file exists. If it does, the script exits immediately. If the lock file does not exist, the script creates it using the touch()
function, and then proceeds to do its work. When the script is finished, it deletes the lock file using the unlink()
function.
Note that this approach is not foolproof, as there may be cases where the lock file is not deleted properly (e.g. due to a system crash or power failure). In such cases, you may need to manually delete the lock file to allow the script to run again.
Comments
Post a Comment