You are here

public function Lock::lock in Ultimate Cron 8.2

Acquire lock.

Parameters

string $job_id: The name of the lock to acquire.

float $timeout: The timeout in seconds for the lock.

Return value

string The lock id acquired.

Overrides LockInterface::lock

File

src/Lock/Lock.php, line 59

Class

Lock
Class for handling lock functions.

Namespace

Drupal\ultimate_cron\Lock

Code

public function lock($job_id, $timeout = 30.0) {

  // First, ensure cleanup.
  if (!isset($this->locks)) {
    $this->locks = array();
    ultimate_cron_register_shutdown_function(array(
      $this,
      'shutdown',
    ));
  }
  $this->connection
    ->setTarget(_ultimate_cron_get_transactional_safe_connection());
  try {

    // First we ensure that previous locks are "removed"
    // if they are expired.
    $this
      ->expire($job_id);

    // Ensure that the timeout is at least 1 ms.
    $timeout = max($timeout, 0.001);
    $expire = microtime(TRUE) + $timeout;

    // Now we try to acquire the lock.
    $lock_id = $this->connection
      ->insert('ultimate_cron_lock')
      ->fields(array(
      'name' => $job_id,
      'current' => 0,
      'expire' => $expire,
    ))
      ->execute();
    $this->locks[$lock_id] = TRUE;
    return $lock_id;
  } catch (PDOException $e) {
    return FALSE;
  } catch (IntegrityConstraintViolationException $e) {
    return FALSE;
  }
}