Skip to content

Instantly share code, notes, and snippets.

@spivurno spivurno/gp-lock.php
Created Oct 27, 2017

Embed
What would you like to do?
Gravity Perks // Lock // Simple Locking System to Prevent Concurrent Actions
/**
* Gravity Perks // Lock // Simple Locking System to Prevent Concurrent Actions
* http://gravitywiz.com./
*/
class GP_Lock {
private $id;
public function __construct( $id = false ) {
if( ! $id ) {
$id = uniqid( 'gpl' );
}
$this->id = $id;
$dirs = wp_upload_dir();
$this->path = $dirs['basedir'] . '/gp-locks/' . $this->id;
$this->flush_expired_lock();
}
public function lock() {
$dirs = wp_upload_dir();
$basepath = $dirs['basedir'] . '/gp-locks';
if( ! file_exists( $basepath ) ) {
mkdir( $basepath );
}
$lock = false;
$timeout = 10; // seconds
$wait = 0.25; // seconds
for( $i = 0; $i < $timeout / $wait; $i++ ) {
$lock = @mkdir( $this->path, 0700 );
if( $lock ) {
break;
}
sleep( $wait );
}
return $lock;
}
public function unlock() {
return @rmdir( $this->path );
}
/**
* PHP may crash before the lock is released. Release the lock after PHP's max execution time has elapsed as a safeguard.
*/
public function flush_expired_lock() {
if( (int) filectime( $this->path ) + (int) ini_get( 'max_execution_time' ) <= time() ) {
$this->unlock();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.