I have a Wordpress plugin that I created that simply exports orders to a 3rd party system. To prevent any possible issues of the plugin running more than once at the same time, I am using the following Mutex code, however on occasion, the mutex file does not remove which stops my plugin from running until I manually remove the file.
<?php
class System_Mutex
{
var $lockName = "";
var $fileName = null;
var $file = null;
public function __construct($lockName) {
$this->lockName = preg_replace('/[^a-z0-9]/', '', $lockName);
$this->getFileName();
}
public function __destruct() {
$this->releaseLock();
}
public function isLocked() {
return ! flock($this->file, LOCK_SH | LOCK_NB);
}
public function getLock() {
return flock($this->file, LOCK_EX | LOCK_NB);
}
public function releaseLock() {
if ( ! is_resource($this->file) ) return true;
$success = flock($this->file, LOCK_UN);
fclose($this->file);
return $success;
}
public function getFileName() {
$this->fileName = dirname(__FILE__) . "/../Locks/" . $this->lockName . ".lock";
if ( ! $this->file = fopen($this->fileName, "c") ) {
throw new Exception("Cannot create temporary lock file.");
}
}
}
The Mutex itself is used like this:
try {
$mutex_id = "ef_stock_sync";
$mutex = new System_Mutex($mutex_id);
//mutex is locked- exit process
if ( $mutex->isLocked() || ! $mutex->getLock() ) {
//
return;
}
} catch ( Exception $e ) {
//
return;
}
$this->_syncStock();
$mutex->releaseLock();
Any idea why this would be happening? I thought that the destructor of the class would ensure it is removed even if the code was to stop halfway?