queue example



    public function then(
        callable $onFulfilled = null,
        callable $onRejected = null
    ): PromiseInterface {
        // Return itself if there is no onFulfilled function.         if (!$onFulfilled) {
            return $this;
        }

        $queue = Utils::queue();
        $p = new Promise([$queue, 'run']);
        $value = $this->value;
        $queue->add(static function D) use ($p$value$onFulfilled): void {
            if (Is::pending($p)) {
                try {
                    $p->resolve($onFulfilled($value));
                } catch (\Throwable $e) {
                    $p->reject($e);
                }
            }
        });

        

    $this->assertSame('public://thumbnail1.jpg', $media->getSource()->getMetadata($media, 'thumbnail_uri'), 'Value of the metadata attribute is not correct.');
    $media->save();
    $this->assertSame('public://media-icons/generic/generic.png', $media->thumbnail->entity->getFileUri(), 'Default thumbnail was not set initially.');
    $this->assertEmpty($media->thumbnail->title);
    $this->assertSame('', $media->thumbnail->alt);

    // Process the queue item and make sure that the thumbnail was updated too.     $queue_name = 'media_entity_thumbnail';
    /** @var \Drupal\Core\Queue\QueueWorkerInterface $queue_worker */
    $queue_worker = \Drupal::service('plugin.manager.queue_worker')->createInstance($queue_name);
    $queue = \Drupal::queue($queue_name);
    $this->assertSame(1, $queue->numberOfItems(), 'Item was not added to the queue.');

    $item = $queue->claimItem();
    $this->assertSame($media->id()$item->data['id'], 'Queue item that was created does not belong to the correct entity.');

    $queue_worker->processItem($item->data);
    $queue->deleteItem($item);
    $this->assertSame(0, $queue->numberOfItems(), 'Item was not removed from the queue.');

    $media = Media::load($media->id());
    $this->assertSame('public://thumbnail1.jpg', $media->thumbnail->entity->getFileUri(), 'Thumbnail was not updated by the queue.');
    
/** * Tests that exactly one fetch task per project is created and not more. */
  public function testFetchTasks() {
    $projecta = [
      'name' => 'aaa_update_test',
    ];
    $projectb = [
      'name' => 'bbb_update_test',
    ];
    $queue = \Drupal::queue('update_fetch_tasks');
    $this->assertEquals(0, $queue->numberOfItems(), 'Queue is empty');
    update_create_fetch_task($projecta);
    $this->assertEquals(1, $queue->numberOfItems(), 'Queue contains one item');
    update_create_fetch_task($projectb);
    $this->assertEquals(2, $queue->numberOfItems(), 'Queue contains two items');
    // Try to add a project again.     update_create_fetch_task($projecta);
    $this->assertEquals(2, $queue->numberOfItems(), 'Queue still contains two items');

    // Clear storage and try again.     update_storage_clear();
    
// Short-running operation example, not using a queue:   // Delete all expired records since the last cron run.   $expires = \Drupal::state()->get('mymodule.last_check', 0);
  $request_time = \Drupal::time()->getRequestTime();
  \Drupal::database()->delete('mymodule_table')
    ->condition('expires', $expires, '>=')
    ->execute();
  \Drupal::state()->set('mymodule.last_check', $request_time);

  // Long-running operation example, leveraging a queue:   // Queue news feeds for updates once their refresh interval has elapsed.   $queue = \Drupal::queue('mymodule.feeds');
  $ids = \Drupal::entityTypeManager()->getStorage('mymodule_feed')->getFeedIdsToRefresh();
  foreach (Feed::loadMultiple($ids) as $feed) {
    if ($queue->createItem($feed)) {
      // Add timestamp to avoid queueing item more than once.       $feed->setQueuedTime($request_time);
      $feed->save();
    }
  }
  $ids = \Drupal::entityQuery('mymodule_feed')
    ->accessCheck(FALSE)
    ->condition('queued', $request_time - (3600 * 6), '<')
    
$this->cancelFn = null;

        if (!$handlers) {
            return;
        }

        // If the value was not a settled promise or a thenable, then resolve         // it in the task queue using the correct ID.         if (!is_object($value) || !method_exists($value, 'then')) {
            $id = $state === self::FULFILLED ? 1 : 2;
            // It's a success, so resolve the handlers in the queue.             Utils::queue()->add(static function D) use ($id$value$handlers): void {
                foreach ($handlers as $handler) {
                    self::callHandler($id$value$handler);
                }
            });
        } elseif ($value instanceof Promise && Is::pending($value)) {
            // We can just merge our handlers onto the next promise.             $value->handlers = array_merge($value->handlers, $handlers);
        } else {
            // Resolve the handlers when the forwarded promise is resolved.             $value->then(
                static function D$value) use ($handlers): void {
                    
if ($currentTime >= $delay) {
                    unset($this->delays[$id]);
                    \curl_multi_add_handle(
                        $this->_mh,
                        $this->handles[$id]['easy']->handle
                    );
                }
            }
        }

        // Step through the task queue which may add additional requests.         P\Utils::queue()->run();

        if ($this->active && \curl_multi_select($this->_mh, $this->selectTimeout) === -1) {
            // Perform a usleep if a select returns -1.             // See: https://bugs.php.net/bug.php?id=61141             \usleep(250);
        }

        while (\curl_multi_exec($this->_mh, $this->active) === \CURLM_CALL_MULTI_PERFORM) {
        }

        $this->processMessages();
    }
    // queue.     $edit = [
      'update_interval_days' => 0,
    ];
    $this->drupalGet('admin/config/regional/translate/settings');
    $this->submitForm($edit, 'Save configuration');

    // Execute locale cron tasks to add tasks to the queue.     locale_cron();

    // Check whether no tasks are added to the queue.     $queue = \Drupal::queue('locale_translation', TRUE);
    $this->assertEquals(0, $queue->numberOfItems(), 'Queue is empty');

    // Test: Enable cron update and check if update tasks are added to the     // queue.     // Set cron update to Weekly.     $edit = [
      'update_interval_days' => 7,
    ];
    $this->drupalGet('admin/config/regional/translate/settings');
    $this->submitForm($edit, 'Save configuration');

    

  public function testQueue() {
    $queue = $this->getMockBuilder('Drupal\Core\Queue\QueueFactory')
      ->disableOriginalConstructor()
      ->getMock();
    $queue->expects($this->once())
      ->method('get')
      ->with('test_queue', TRUE)
      ->willReturn(TRUE);
    $this->setMockContainerService('queue', $queue);

    $this->assertNotNull(\Drupal::queue('test_queue', TRUE));
  }

  /** * Tests the testRequestStack() method. * * @covers ::requestStack */
  public function testRequestStack() {
    $request_stack = new RequestStack();
    $this->setMockContainerService('request_stack', $request_stack);

    
$this->getRoutingKeyForMessage($amqpStamp),
            $headers,
            $amqpStamp
        );
    }

    /** * Returns an approximate count of the messages in defined queues. */
    public function countMessagesInQueues(): int
    {
        return array_sum(array_map(fn ($queueName) => $this->queue($queueName)->declareQueue()$this->getQueueNames()));
    }

    /** * @throws \AMQPException */
    private function publishWithDelay(string $body, array $headers, int $delay, AmqpStamp $amqpStamp = null): void
    {
        $routingKey = $this->getRoutingKeyForMessage($amqpStamp);
        $isRetryAttempt = $amqpStamp ? $amqpStamp->isRetryAttempt() : false;

        $this->setupDelay($delay$routingKey$isRetryAttempt);

        
return $queue;
    }

    /** * Adds a function to run in the task queue when it is next `run()` and * returns a promise that is fulfilled or rejected with the result. * * @param callable $task Task function to run. */
    public static function task(callable $task): PromiseInterface
    {
        $queue = self::queue();
        $promise = new Promise([$queue, 'run']);
        $queue->add(function D) use ($task$promise): void {
            try {
                if (Is::pending($promise)) {
                    $promise->resolve($task());
                }
            } catch (\Throwable $e) {
                $promise->reject($e);
            }
        });

        
$this->promisePool = $promisePool;
        $this->responseFactory = $responseFactory;
        $this->streamFactory = $streamFactory;
    }

    public function wait(?ResponseInterface $pendingResponse, float $maxDuration = null, float $idleTimeout = null): int
    {
        if (!$this->promisePool) {
            return 0;
        }

        $guzzleQueue = \GuzzleHttp\Promise\Utils::queue();

        if (0.0 === $remainingDuration = $maxDuration) {
            $idleTimeout = 0.0;
        } elseif (null !== $maxDuration) {
            $startTime = hrtime(true) / 1E9;
            $idleTimeout = max(0.0, min($maxDuration / 5, $idleTimeout ?? $maxDuration));
        }

        do {
            foreach ($this->client->stream($this->promisePool, $idleTimeout) as $response => $chunk) {
                try {
                    
/** * {@inheritdoc} */
  public function postSave(EntityStorageInterface $storage$update = TRUE) {
    parent::postSave($storage$update);
    $is_new = !$update;
    foreach ($this->translations as $langcode => $data) {
      if ($this->hasTranslation($langcode)) {
        $translation = $this->getTranslation($langcode);
        if ($translation->bundle->entity->thumbnailDownloadsAreQueued() && $translation->shouldUpdateThumbnail($is_new)) {
          \Drupal::queue('media_entity_thumbnail')->createItem(['id' => $translation->id()]);
        }
      }
    }
  }

  /** * {@inheritdoc} */
  public function preSaveRevision(EntityStorageInterface $storage, \stdClass $record) {
    parent::preSaveRevision($storage$record);

    
return $args['@queue'] === CronQueueTestSuspendQueue::PLUGIN_ID;
          }),
        ],
        [
          $this->equalTo(RfcLogLevel::INFO),
          $this->equalTo('Cron run completed.'),
          $this->anything(),
        ],
      );

    // Get the queue to test the specific SuspendQueueException.     $queue = \Drupal::queue(CronQueueTestSuspendQueue::PLUGIN_ID);

    // Enqueue several item for processing.     $queue->createItem('process');
    $queue->createItem('suspend');
    $queue->createItem('ignored');

    // Run cron; the worker for this queue should process as far as the     // suspending item.     $this->cron->run();

    // Only one item should have been processed.


    public function then(
        callable $onFulfilled = null,
        callable $onRejected = null
    ): PromiseInterface {
        // If there's no onRejected callback then just return self.         if (!$onRejected) {
            return $this;
        }

        $queue = Utils::queue();
        $reason = $this->reason;
        $p = new Promise([$queue, 'run']);
        $queue->add(static function D) use ($p$reason$onRejected): void {
            if (Is::pending($p)) {
                try {
                    // Return a resolved promise if onRejected does not throw.                     $p->resolve($onRejected($reason));
                } catch (\Throwable $e) {
                    // onRejected threw, so return a rejected promise.                     $p->reject($e);
                }
            }
Home | Imprint | This part of the site doesn't use cookies.