As modern web development continues to evolve, managing asynchronous tasks has become a critical aspect of building scalable and maintainable applications. Fortunately, Drupal Core provides a built-in queue system that allows you to offload tasks to a separate process, freeing up your main thread to handle user requests. In this tutorial, we'll explore how to use the Drupal Core queue to perform asynchronous tasks in your Drupal 10 project.
What is the Drupal Core Queue?
The Drupal Core queue is a built-in system that allows you to submit tasks (jobs) to a dedicated worker process. This process, separate from your main web application, executes the tasks asynchronously, ensuring that your application remains responsive and efficient.
When to Use the Drupal Core Queue?
The Drupal Core queue is particularly useful in situations where:
- You need to perform CPU-intensive or long-running tasks that might slow down your application.
- You want to decouple tasks from your main web request-response cycle, ensuring that users don't experience delays or timeouts.
- You need to handle tasks that require specific permissions or privileges, such as sending notifications or sending emails.
Creating a Job
Let's create a job that sends a notification via email. We'll define a `SendNotificationJob` class that implements the `Drupal\Core\Queue\QueueWorkerInterface`. This class should be placed inside the `src/Queue` directory of your module:
// mymodule/src/Queue/SendNotificationJob.php
namespace Drupal\mymodule\Queue;
use Drupal\Core\Queue\QueueWorkerInterface;
use Drupal\Core\Queue\QueueInterface;
use Drupal\Core\Mail\MailManagerInterface;
use Drupal\Core\Mail\MailInterface;
class SendNotificationJob implements QueueWorkerInterface {
public function process(QueueInterface $queue) {
// Get the mail manager service
$mail_manager = \Drupal::service('plugin.manager.mail');
// Get the mail plugin
$mail_plugin = $mail_manager->getPlugin('my_email_plugin');
// Send the email
$mail_plugin->mail('my_email_template', 'user@example.com', 'Hello, world!');
}
}
Defining the Queue
We need to define the queue in our module's `mymodule.info.yml` file:
// mymodule/mymodule.info.yml
name: My Module
description: My module description
package: Custom
type: module
core: 10.x
queue:
my_queue:
class: \Drupal\mymodule\Queue\SendNotificationJob
cron: 0 0 * * * *
Submitting a Job
Now that we have our job defined, let's submit it to the queue. We'll use the `Drupal\Core\Queue\Queue` service to enqueue the job:
// mymodule/src/Controller/MyController.php
namespace Drupal\mymodule\Controller;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Queue\Queue;
class MyController extends ControllerBase {
public function myMethod() {
// Get the queue service
$queue = \Drupal::service('queue');
// Create a new job
$job = new SendNotificationJob();
// Enqueue the job
$queue->createItem($job);
}
}