You are here

public static function UltimateCronLock::lock in Ultimate Cron 7.2

Acquire lock.

Parameters

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

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

Return value

string The lock id acquired.

File

./ultimate_cron.lock.inc, line 53
A database-mediated implementation of a locking mechanism.

Class

UltimateCronLock
Class for handling lock functions.

Code

public static function lock($name, $timeout = 30.0) {

  // First, ensure cleanup.
  if (!isset(self::$locks)) {
    self::$locks = array();
    ultimate_cron_register_shutdown_function(array(
      'UltimateCronLock',
      'shutdown',
    ));
  }
  $target = _ultimate_cron_get_transactional_safe_connection();
  try {

    // First we ensure that previous locks are "removed"
    // if they are expired.
    self::expire($name);

    // 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 = db_insert('ultimate_cron_lock', array(
      'target' => $target,
    ))
      ->fields(array(
      'name' => $name,
      'current' => 0,
      'expire' => $expire,
    ))
      ->execute();
    self::$locks[$lock_id] = TRUE;
    return $lock_id;
  } catch (PDOException $e) {
    return FALSE;
  }
}