Created
October 27, 2017 14:04
-
-
Save spivurno/1d17bc4565f1077dc7f7bd5cb1ec4f82 to your computer and use it in GitHub Desktop.
Gravity Perks // Lock // Simple Locking System to Prevent Concurrent Actions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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