本文整理汇总了PHP中Drupal\Core\Lock\LockBackendInterface::acquire方法的典型用法代码示例。如果您正苦于以下问题:PHP LockBackendInterface::acquire方法的具体用法?PHP LockBackendInterface::acquire怎么用?PHP LockBackendInterface::acquire使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Drupal\Core\Lock\LockBackendInterface
的用法示例。
在下文中一共展示了LockBackendInterface::acquire方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: execute
/**
* {@inheritdoc}
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$io = new DrupalStyle($input, $output);
$modules = $input->getArgument('module');
if (!$this->lock->acquire('cron', 900.0)) {
$io->warning($this->trans('commands.cron.execute.messages.lock'));
return 1;
}
if (in_array('all', $modules)) {
$modules = $this->moduleHandler->getImplementations('cron');
}
foreach ($modules as $module) {
if (!$this->moduleHandler->implementsHook($module, 'cron')) {
$io->warning(sprintf($this->trans('commands.cron.execute.messages.module-invalid'), $module));
continue;
}
try {
$io->info(sprintf($this->trans('commands.cron.execute.messages.executing-cron'), $module));
$this->moduleHandler->invoke($module, 'cron');
} catch (\Exception $e) {
watchdog_exception('cron', $e);
$io->error($e->getMessage());
}
}
$this->state->set('system.cron_last', REQUEST_TIME);
$this->lock->release('cron');
$this->chainQueue->addCommand('cache:rebuild', ['cache' => 'all']);
$io->success($this->trans('commands.cron.execute.messages.success'));
return 0;
}
示例2: initialize
/**
* Initializes the config importer in preparation for processing a batch.
*
* @return array
* An array of \Drupal\Core\Config\ConfigImporter method names and callables
* that are invoked to complete the import. If there are modules or themes
* to process then an extra step is added.
*
* @throws \Drupal\Core\Config\ConfigImporterException
* If the configuration is already importing.
*/
public function initialize()
{
$this->createExtensionChangelist();
// Ensure that the changes have been validated.
$this->validate();
if (!$this->lock->acquire(static::LOCK_NAME)) {
// Another process is synchronizing configuration.
throw new ConfigImporterException(sprintf('%s is already importing', static::LOCK_NAME));
}
$sync_steps = array();
$modules = $this->getUnprocessedExtensions('module');
foreach (array('install', 'uninstall') as $op) {
$this->totalExtensionsToProcess += count($modules[$op]);
}
$themes = $this->getUnprocessedExtensions('theme');
foreach (array('install', 'uninstall') as $op) {
$this->totalExtensionsToProcess += count($themes[$op]);
}
// We have extensions to process.
if ($this->totalExtensionsToProcess > 0) {
$sync_steps[] = 'processExtensions';
}
$sync_steps[] = 'processConfigurations';
// Allow modules to add new steps to configuration synchronization.
$this->moduleHandler->alter('config_import_steps', $sync_steps, $this);
$sync_steps[] = 'finish';
return $sync_steps;
}
示例3: run
/**
* {@inheritdoc}
*/
public function run()
{
// Allow execution to continue even if the request gets cancelled.
@ignore_user_abort(TRUE);
// Force the current user to anonymous to ensure consistent permissions on
// cron runs.
$this->accountSwitcher->switchTo(new AnonymousUserSession());
// Try to allocate enough time to run all the hook_cron implementations.
drupal_set_time_limit(240);
$return = FALSE;
// Try to acquire cron lock.
if (!$this->lock->acquire('cron', 900.0)) {
// Cron is still running normally.
$this->logger->warning('Attempting to re-run cron while it is already running.');
} else {
$this->invokeCronHandlers();
$this->setCronLastTime();
// Release cron lock.
$this->lock->release('cron');
// Return TRUE so other functions can check if it did run successfully
$return = TRUE;
}
// Process cron queues.
$this->processQueues();
// Restore the user.
$this->accountSwitcher->switchBack();
return $return;
}
示例4: run
/**
* {@inheritdoc}
*/
public function run()
{
// Allow execution to continue even if the request gets cancelled.
@ignore_user_abort(TRUE);
// Prevent session information from being saved while cron is running.
$original_session_saving = $this->sessionManager->isEnabled();
$this->sessionManager->disable();
// Force the current user to anonymous to ensure consistent permissions on
// cron runs.
$original_user = $this->currentUser->getAccount();
$this->currentUser->setAccount(new AnonymousUserSession());
// Try to allocate enough time to run all the hook_cron implementations.
drupal_set_time_limit(240);
$return = FALSE;
// Try to acquire cron lock.
if (!$this->lock->acquire('cron', 240.0)) {
// Cron is still running normally.
watchdog('cron', 'Attempting to re-run cron while it is already running.', array(), WATCHDOG_WARNING);
} else {
$this->invokeCronHandlers();
$this->setCronLastTime();
// Release cron lock.
$this->lock->release('cron');
// Return TRUE so other functions can check if it did run successfully
$return = TRUE;
}
// Process cron queues.
$this->processQueues();
// Restore the user.
$this->currentUser->setAccount($original_user);
if ($original_session_saving) {
$this->sessionManager->enable();
}
return $return;
}
示例5: rebuild
/**
* {@inheritdoc}
*/
public function rebuild()
{
if ($this->building) {
throw new \RuntimeException('Recursive router rebuild detected.');
}
if (!$this->lock->acquire('router_rebuild')) {
// Wait for another request that is already doing this work.
// We choose to block here since otherwise the routes might not be
// available, resulting in a 404.
$this->lock->wait('router_rebuild');
return FALSE;
}
$this->building = TRUE;
$collection = new RouteCollection();
foreach ($this->getRouteDefinitions() as $routes) {
// The top-level 'routes_callback' is a list of methods in controller
// syntax, see \Drupal\Core\Controller\ControllerResolver. These methods
// should return a set of \Symfony\Component\Routing\Route objects, either
// in an associative array keyed by the route name, which will be iterated
// over and added to the collection for this provider, or as a new
// \Symfony\Component\Routing\RouteCollection object, which will be added
// to the collection.
if (isset($routes['route_callbacks'])) {
foreach ($routes['route_callbacks'] as $route_callback) {
$callback = $this->controllerResolver->getControllerFromDefinition($route_callback);
if ($callback_routes = call_user_func($callback)) {
// If a RouteCollection is returned, add the whole collection.
if ($callback_routes instanceof RouteCollection) {
$collection->addCollection($callback_routes);
} else {
foreach ($callback_routes as $name => $callback_route) {
$collection->add($name, $callback_route);
}
}
}
}
unset($routes['route_callbacks']);
}
foreach ($routes as $name => $route_info) {
$route_info += array('defaults' => array(), 'requirements' => array(), 'options' => array());
$route = new Route($route_info['path'], $route_info['defaults'], $route_info['requirements'], $route_info['options']);
$collection->add($name, $route);
}
}
// DYNAMIC is supposed to be used to add new routes based upon all the
// static defined ones.
$this->dispatcher->dispatch(RoutingEvents::DYNAMIC, new RouteBuildEvent($collection));
// ALTER is the final step to alter all the existing routes. We cannot stop
// people from adding new routes here, but we define two separate steps to
// make it clear.
$this->dispatcher->dispatch(RoutingEvents::ALTER, new RouteBuildEvent($collection));
$this->checkProvider->setChecks($collection);
$this->dumper->addRoutes($collection);
$this->dumper->dump();
$this->lock->release('router_rebuild');
$this->dispatcher->dispatch(RoutingEvents::FINISHED, new Event());
$this->building = FALSE;
$this->rebuildNeeded = FALSE;
return TRUE;
}
示例6: lockPersist
/**
* Creates a lock that will persist across requests.
*
* @param string $lock_name
* The name of the persistent lock to acquire.
*
* @return string
* The text to display.
*/
public function lockPersist($lock_name)
{
if ($this->persistentLock->acquire($lock_name)) {
return ['#markup' => 'TRUE: Lock successfully acquired in SystemTestController::lockPersist()'];
} else {
return ['#markup' => 'FALSE: Lock not acquired in SystemTestController::lockPersist()'];
}
}
示例7: execute
/**
* Executes a callback.
*
* @param \Drupal\feeds\FeedInterface $feeds_feed
* The Feed we are executing a job for.
* @param \Symfony\Component\HttpFoundation\Request $request
* The request object to grab POST params from.
*
* @todo Configure a time limit.
* @todo Really awesome error handling.
*/
public function execute(FeedInterface $feeds_feed, Request $request)
{
$cid = 'feeds_feed:' . $feeds_feed->id();
if ($token = $request->request->get('token') && ($job = $this->state->get($cid))) {
if ($job['token'] == $token && ($lock = $this->lockBackend->acquire($cid))) {
$method = $job['method'];
$this->state->delete($cid);
ignore_user_abort(TRUE);
set_time_limit(0);
while ($feeds_feed->{$method}() != StateInterface::BATCH_COMPLETE) {
// Reset static caches in between runs to avoid memory leaks.
drupal_reset_static();
}
$this->lockBackend->release($cid);
}
}
}
示例8: getMails
/**
* {@inheritdoc}
*/
public function getMails($limit = self::UNLIMITED, $conditions = array())
{
$messages = array();
// Continue to support 'nid' as a condition.
if (!empty($conditions['nid'])) {
$conditions['entity_type'] = 'node';
$conditions['entity_id'] = $conditions['nid'];
unset($conditions['nid']);
}
// Add default status condition if not set.
if (!isset($conditions['status'])) {
$conditions['status'] = array(SpoolStorageInterface::STATUS_PENDING, SpoolStorageInterface::STATUS_IN_PROGRESS);
}
// Special case for the status condition, the in progress actually only
// includes spool items whose locking time has expired. So this need to build
// an OR condition for them.
$status_or = new Condition('OR');
$statuses = is_array($conditions['status']) ? $conditions['status'] : array($conditions['status']);
foreach ($statuses as $status) {
if ($status == SpoolStorageInterface::STATUS_IN_PROGRESS) {
$status_or->condition((new Condition('AND'))->condition('status', $status)->condition('s.timestamp', $this->getExpirationTime(), '<'));
} else {
$status_or->condition('status', $status);
}
}
unset($conditions['status']);
$query = $this->connection->select('simplenews_mail_spool', 's')->fields('s')->condition($status_or)->orderBy('s.timestamp', 'ASC');
// Add conditions.
foreach ($conditions as $field => $value) {
$query->condition($field, $value);
}
/* BEGIN CRITICAL SECTION */
// The semaphore ensures that multiple processes get different message ID's,
// so that duplicate messages are not sent.
if ($this->lock->acquire('simplenews_acquire_mail')) {
// Get message id's
// Allocate messages
if ($limit > 0) {
$query->range(0, $limit);
}
foreach ($query->execute() as $message) {
if (Unicode::strlen($message->data)) {
$message->data = unserialize($message->data);
} else {
$message->data = simplenews_subscriber_load_by_mail($message->mail);
}
$messages[$message->msid] = $message;
}
if (count($messages) > 0) {
// Set the state and the timestamp of the messages
$this->updateMails(array_keys($messages), array('status' => SpoolStorageInterface::STATUS_IN_PROGRESS));
}
$this->lock->release('simplenews_acquire_mail');
}
/* END CRITICAL SECTION */
return new SpoolList($messages);
}
示例9: delete
/**
* Deletes data from the store for a given key and releases the lock on it.
*
* @param string $key
* The key of the data to delete.
*/
public function delete($key)
{
if (!$this->lockBackend->acquire($key)) {
$this->lockBackend->wait($key);
if (!$this->lockBackend->acquire($key)) {
throw new TempStoreException(String::format("Couldn't acquire lock to delete item %key from %collection temporary storage.", array('%key' => $key, '%collection' => $this->storage->getCollectionName())));
}
}
$this->storage->delete($key);
$this->lockBackend->release($key);
}
示例10: delete
/**
* Deletes data from the store for a given key and releases the lock on it.
*
* @param string $key
* The key of the data to delete.
*/
public function delete($key)
{
if (!$this->lockBackend->acquire($key)) {
$this->lockBackend->wait($key);
if (!$this->lockBackend->acquire($key)) {
throw new TempStoreException("Couldn't acquire lock to delete item '{$key}' from {$this->storage->getCollectionName()} temporary storage.");
}
}
$this->storage->delete($key);
$this->lockBackend->release($key);
}
示例11: menuLinksRebuild
/**
* Perform menu-specific rebuilding.
*/
protected function menuLinksRebuild()
{
if ($this->lock->acquire(__FUNCTION__)) {
$transaction = db_transaction();
try {
// Ensure the menu links are up to date.
$this->menuLinkManager->rebuild();
// Ignore any database replicas temporarily.
db_ignore_replica();
} catch (\Exception $e) {
$transaction->rollback();
watchdog_exception('menu', $e);
}
$this->lock->release(__FUNCTION__);
} else {
// Wait for another request that is already doing this work.
// We choose to block here since otherwise the router item may not
// be available during routing resulting in a 404.
$this->lock->wait(__FUNCTION__);
}
}
示例12: menuLinksRebuild
/**
* Perform menu-specific rebuilding.
*/
protected function menuLinksRebuild()
{
if ($this->lock->acquire(__FUNCTION__)) {
$transaction = db_transaction();
try {
// Ensure the menu links are up to date.
menu_link_rebuild_defaults();
// Clear the menu cache.
menu_cache_clear_all();
// Track which menu items are expanded.
_menu_update_expanded_menus();
} catch (\Exception $e) {
$transaction->rollback();
watchdog_exception('menu', $e);
}
$this->lock->release(__FUNCTION__);
} else {
// Wait for another request that is already doing this work.
// We choose to block here since otherwise the router item may not
// be available during routing resulting in a 404.
$this->lock->wait(__FUNCTION__);
}
}
示例13: delete
/**
* Deletes data from the store for a given key and releases the lock on it.
*
* @param string $key
* The key of the data to delete.
*
* @return bool
* TRUE if the object was deleted or does not exist, FALSE if it exists but
* is not owned by $this->owner.
*/
public function delete($key)
{
$key = $this->createkey($key);
if (!($object = $this->storage->get($key))) {
return TRUE;
} elseif ($object->owner != $this->getOwner()) {
return FALSE;
}
if (!$this->lockBackend->acquire($key)) {
$this->lockBackend->wait($key);
if (!$this->lockBackend->acquire($key)) {
throw new TempStoreException(SafeMarkup::format("Couldn't acquire lock to delete item %key from %collection temporary storage.", array('%key' => $key, '%collection' => $this->storage->getCollectionName())));
}
}
$this->storage->delete($key);
$this->lockBackend->release($key);
return TRUE;
}
示例14: delete
/**
* Deletes data from the store for a given key and releases the lock on it.
*
* @param string $key
* The key of the data to delete.
*
* @return bool
* TRUE if the object was deleted or does not exist, FALSE if it exists but
* is not owned by $this->owner.
*/
public function delete($key)
{
$key = $this->createkey($key);
if (!($object = $this->storage->get($key))) {
return TRUE;
} elseif ($object->owner != $this->getOwner()) {
return FALSE;
}
if (!$this->lockBackend->acquire($key)) {
$this->lockBackend->wait($key);
if (!$this->lockBackend->acquire($key)) {
throw new TempStoreException("Couldn't acquire lock to delete item '{$key}' from '{$this->storage->getCollectionName()}' temporary storage.");
}
}
$this->storage->delete($key);
$this->lockBackend->release($key);
return TRUE;
}
示例15: updateCache
/**
* Writes a value to the persistent cache immediately.
*
* @param bool $lock
* (optional) Whether to acquire a lock before writing to cache. Defaults to
* TRUE.
*/
protected function updateCache($lock = TRUE)
{
$data = array();
foreach ($this->keysToPersist as $offset => $persist) {
if ($persist) {
$data[$offset] = $this->storage[$offset];
}
}
if (empty($data) && empty($this->keysToRemove)) {
return;
}
// Lock cache writes to help avoid stampedes.
$cid = $this->getCid();
$lock_name = $this->normalizeLockName($cid . ':' . __CLASS__);
if (!$lock || $this->lock->acquire($lock_name)) {
// Set and delete operations invalidate the cache item. Try to also load
// an eventually invalidated cache entry, only update an invalidated cache
// entry if the creation date did not change as this could result in an
// inconsistent cache.
if ($cache = $this->cache->get($cid, $this->cacheInvalidated)) {
if ($this->cacheInvalidated && $cache->created != $this->cacheCreated) {
// We have invalidated the cache in this request and got a different
// cache entry. Do not attempt to overwrite data that might have been
// changed in a different request. We'll let the cache rebuild in
// later requests.
$this->cache->delete($cid);
$this->lock->release($lock_name);
return;
}
$data = array_merge($cache->data, $data);
}
// Remove keys marked for deletion.
foreach ($this->keysToRemove as $delete_key) {
unset($data[$delete_key]);
}
$this->cache->set($cid, $data, Cache::PERMANENT, $this->tags);
if ($lock) {
$this->lock->release($lock_name);
}
}
$this->keysToPersist = array();
$this->keysToRemove = array();
}