ActionScheduler_OptionLock::set │ public │ WC 1.0

Set a lock using options for a given amount of time (60 seconds by default).

Using an autoloaded option avoids running database queries or other resource intensive tasks on frequently triggered hooks, like 'init' or 'shutdown'.

For example, ActionScheduler_QueueRunner->maybe_dispatch_async_request() uses a lock to avoid calling ActionScheduler_QueueRunner->has_maximum_concurrent_batches() every time the 'shutdown', hook is triggered, because that method calls ActionScheduler_QueueRunner->store->get_claim_count() to find the current number of claims in the database.

Метод класса: ActionScheduler_OptionLock{}

Хуков нет.

Возвращает

null. Ничего (null).

Использование

$ActionScheduler_OptionLock = new ActionScheduler_OptionLock();
$ActionScheduler_OptionLock->set( $lock_type );
$lock_type(строка) (обязательный)
A string to identify different lock types.

Код ActionScheduler_OptionLock::set() WC 11.2.2

public function set( $lock_type ) {
	global $wpdb;

	$now                 = time();
	$lock_key            = $this->get_key( $lock_type );
	$existing_lock_value = $this->get_existing_lock( $lock_type, $now );
	$new_lock_value      = $this->new_lock_value( $lock_type, $now );

	// The lock may not exist yet, or may have been deleted.
	if ( null === $existing_lock_value ) {
		$inserted = (bool) $wpdb->insert(
			$wpdb->options,
			array(
				'option_name'  => $lock_key,
				'option_value' => $new_lock_value,
				'autoload'     => 'no',
			)
		);

		// Sync cache as necessary.
		if ( $inserted ) {
			$ttl = $this->get_expiration_from( $new_lock_value ) - $now;
			if ( $ttl > 0 ) {
				wp_cache_set( $lock_key, $new_lock_value, 'action_scheduler_locks', $ttl );
			}
		}

		return $inserted;
	}

	if ( $this->get_expiration_from( $existing_lock_value ) >= $now ) {
		return false;
	}

	// Otherwise, try to obtain the lock.
	$updated = (bool) $wpdb->update(
		$wpdb->options,
		array( 'option_value' => $new_lock_value ),
		array(
			'option_name'  => $lock_key,
			'option_value' => $existing_lock_value,
		)
	);

	// Sync cache as necessary.
	if ( $updated ) {
		$ttl = $this->get_expiration_from( $new_lock_value ) - $now;
		if ( $ttl > 0 ) {
			wp_cache_set( $lock_key, $new_lock_value, 'action_scheduler_locks', $ttl );
		}
	} else {
		// Compare-and-swap failed — another process acquired the lock between our read and write.
		// Invalidate cache: the expired value may still be live in WP object cache (TTL=1 edge case) before the winner's wp_cache_set executes.
		wp_cache_delete( $lock_key, 'action_scheduler_locks' );
	}

	return $updated;
}