Skip to main content

Leverage Queue API in Drupal to handle resource intensive tasks

Leverage Queue API in Drupal to handle resource intensive tasks

Queue API in Drupal

Unlock the Power of Drupal with This useful Queue API Trick!

Drupal's versatility and powerful infrastructure enable developers to create complex online applications. The Queue API is a strong feature in Drupal 10, designed to efficiently handle costly back-end processes. This article will demonstrate how to create and execute a queue using the Queue API in Drupal.

What is the Queue API in Drupal?

Drupal's Queue API is a system that allows you manage activities that can be performed later, allowing you to postpone costly actions that do not need to be finished right now. This is especially handy for things like sending emails, updating large datasets, or conducting complex calculations that might otherwise slow down your website's speed if done during a page request.

Benefits of Using the Queue API in Drupal

  • Improved Performance: By offloading resource-intensive tasks, you can improve the overall performance and responsiveness of your site.
  • Scalability: The Queue API allows you to handle large volumes of tasks by processing them in the background.
  • Reliability: Tasks are less likely to fail or time out when processed in a queue.

Step-by-Step Guide to Using the Queue API in Drupal 10

1. Create a Custom Module

First, create a custom module to implement the Queue API. For this example, we'll create a module named `bhimmu`.

Directory Structure:

/modules/custom/bhimmu
   ├── bhimmu.info.yml
   ├── bhimmu.module
   ├── src/Plugin/QueueWorker/BhimmuQueue.php
# modules/custom/bhimmu/bhimmu.info.yml:
name: 'Bhimmu'
type: module
description: 'A module to demonstrate the use of the Queue API in Drupal.'
core_version_requirement: ^10
package: Custom
# modules/custom/bhimmu/bhimmu.module
<?php

/**
 * Implements hook_cron().
 */
function bhimmu_cron() {
  // Get the queue service.
  $queue = \Drupal::queue('bhimmu_queue');
  $queue->createQueue();
  // Create item in the queue. Here I am pushing only one item but multiple items can be pushed using loop.
  $queue->createItem(['message' => 'This is a queued message from yogable module.']);
}

2. Define the Queue Worker

Create the `BhimmuQueue` class in the `src/Plugin/QueueWorker` directory.

# web/modules/custom/bhimmu/src/Plugin/QueueWorker/BhimmuQueue.php

<?php

namespace Drupal\bhimmu\Plugin\QueueWorker;

use Drupal\Core\Logger\LoggerChannelFactoryInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Queue\QueueWorkerBase;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Defines 'bhimmu_queue' queue worker.
 *
 * @QueueWorker(
 *   id = "bhimmu_queue",
 *   title = @Translation("Bhimmu Queue"),
 *   cron = {"time" = 60},
 * )
 */
final class BhimmuQueue extends QueueWorkerBase implements ContainerFactoryPluginInterface {

  /**
   * Constructs a new BhimmuQueue instance.
   */
  public function __construct(
    array $configuration,
    $plugin_id,
    $plugin_definition,
    private readonly LoggerChannelFactoryInterface $loggerFactory,
  ) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition): self {
    return new self(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('logger.factory'),
    );
  }

  /**
   * {@inheritdoc}
   */
  public function processItem($data): void {
    // Process the queued item.
    $this->loggerFactory->get('bhimmu')
      ->info('Processing message: @message', ['@message' => $data['message']]);
  }

}

3. Running the Queue

To execute the queue worker, you can either wait for the cron to run or execute it manually using Drush:
 

drush cron

Conclusion

Using the Queue API in Drupal 10 is an effective way to manage and execute costly back-end jobs without affecting the performance of your website. By following this guide, you can create and execute queues to handle various tasks efficiently. Implementing the Queue API will help you build a more scalable and reliable Drupal application.

Unlock the full potential of Drupal by leveraging the Queue API, and ensure your website performs optimally even under heavy load. Happy queuing!