Skip to content

Instantly share code, notes, and snippets.

@yesnik
Created September 6, 2019 09:35
Show Gist options
  • Save yesnik/4c4e738fc41a7553f1f07bd73c2a8e33 to your computer and use it in GitHub Desktop.
Save yesnik/4c4e738fc41a7553f1f07bd73c2a8e33 to your computer and use it in GitHub Desktop.
PHP Unique process
<?php
/**
* This class allows us to run only one instance of the process
*
* Example:
*
* $uniqueProcess = new UniqueProcess('/var/tmp/some_process_name.lock');
* if (!$uniqueProcess->begin()) {
* die();
* }
*
* someLongProcess();
*
* $uniqueProcess->finish();
*
* Class UniqueProcess
*/
class UniqueProcess
{
/**
* Pointer to lock file
* @var resource
*/
protected $lockFilePointer;
/**
* Path to lock file
* @var string
*/
protected $fileLockPath;
public function __construct($fileLockPath)
{
$this->fileLockPath = $fileLockPath;
}
/**
* Method returns true if file was locked, false otherwise
* @return bool
*/
public function begin()
{
if (!$this->lockFile()) {
return false;
}
return true;
}
/**
* Method releases lock
*/
public function finish()
{
$this->releaseLock();
}
/**
* Method returns true if file was locked
* @return bool
* @throws Exception
*/
protected function lockFile()
{
$this->lockFilePointer = fopen($this->fileLockPath, 'w');
if ($this->lockFilePointer === false) {
throw new Exception('Unable to create/open lock file');
}
return flock($this->lockFilePointer, LOCK_EX | LOCK_NB);
}
/**
* Release file lock even in case of Fatal error
*/
public function __destruct()
{
$this->releaseLock();
}
/**
* Method releases lock
*/
protected function releaseLock()
{
if (is_resource($this->lockFilePointer)) {
fclose($this->lockFilePointer);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment