bonsaicode/filelock

Used to prevent a script from being run more than once at the same time by providing mutex functionality via locking a file on the local machine.

1.0.3 2019-08-15 04:40 UTC

This package is auto-updated.

Last update: 2024-06-15 15:44:19 UTC


README

Used to prevent a script from being run more than once at the same time by providing mutex functionality via locking a file on the local machine.

Scenario:

1. You run php script A and it acquires the lock having a given name, e.g. "lockA"
2. You try to run script A again while it is still running.  It tries to acquire the same "lockA", but cannot because the first script has the lock.
3. After the first script A ends, the "lockA" is released, and then you could run the script again.

When a lock is released, the underlying lock file is removed. If the script dies unexpectedly, the lockfile remains but can be relocked by the next script.

This class is intended for single server environments or when you know the process will only run on one server.

DO NOT use this if you are running in a multi-server environment where duplicate VMs could be dynamically created, e.g. auto scaling environment. Otherwise the same process could run at the same time on multiple servers. Therefore we do not use sys_get_temp_dir() for the lockfile directory because the server could change between requests. If you are running in a multi-server environment with dynamically created VMs, please use the BonsaiCode\Redis::lockAcquire and BonsaiCode\Redis::lockRelease methods (with a redis service)

Note: This does not work on Windows localhost w/NGINX:

  1. the script will wait until any lockfile is released instead of the intended named lockfile.
  2. two scripts won't run at same time, but one will wait for the other instead of exiting

Dependencies:

This class assumes a LOCK_DIR constant is defined with a value of the directory in which to create the lock file, e.g.:
     const LOCK_DIR = '/var/www/mysite.com/locks';

LOCK_DIR should be located outside of any web/code directories so that the code can be updated without affecting any existing lock files.
LOCK_DIR MUST BE WRITABLE BY NGINX.

Requirements

  • PHP 7.1 or higher

Installation

To install the module, run the following command in the console:

$ composer require "bonsaicode/filelock"

Usage

<?php

$lock       = new BonsaiCode\FileLock( 'MyLock' );
$lockStatus = $lock->acquire();
if( $lockStatus === -1 ) {
	echo "Script already running\n";
	exit();
} else if( $lockStatus === -2 ) {
	echo "Cannot open lock, permission problem?\n";
	exit();
}

# Your process code here...

$lock->release();
?>