Jobby\Helper::acquireLock PHP Method

acquireLock() public method

public acquireLock ( string $lockFile )
$lockFile string
    public function acquireLock($lockFile)
    {
        if (array_key_exists($lockFile, $this->lockHandles)) {
            throw new Exception("Lock already acquired (Lockfile: {$lockFile}).");
        }
        if (!file_exists($lockFile) && !touch($lockFile)) {
            throw new Exception("Unable to create file (File: {$lockFile}).");
        }
        $fh = fopen($lockFile, 'r+');
        if ($fh === false) {
            throw new Exception("Unable to open file (File: {$lockFile}).");
        }
        $attempts = 5;
        while ($attempts > 0) {
            if (flock($fh, LOCK_EX | LOCK_NB)) {
                $this->lockHandles[$lockFile] = $fh;
                ftruncate($fh, 0);
                fwrite($fh, getmypid());
                return;
            }
            usleep(250);
            --$attempts;
        }
        throw new InfoException("Job is still locked (Lockfile: {$lockFile})!");
    }

Usage Example

Example #1
0
 /**
  * @covers Jobby\Helper::acquireLock
  */
 public function testAquireLockShouldFailOnSecondTry()
 {
     $lockFile = $this->tmpDir . "/test.lock";
     $this->helper->acquireLock($lockFile);
     $this->setExpectedException("Jobby\\Exception");
     $this->helper->acquireLock($lockFile);
 }
All Usage Examples Of Jobby\Helper::acquireLock