blog-banner

How to Create Queue Worker in Drupal 8

  • Drupal 8
  • Drupal Planet

Drupal Queue Worker

The drupal queue API allows placing items in a queue and processing them later. If you have a task that must be done regularly and takes more time to complete then Cron queue might be the better solution.

In Drupal 8, hook_cron_queue_info() has been replaced by QueueWorker Plugin. Define the queue worker by creating a QueueWorker folder inside the Plugin folder. In the below example, I create a form for sending the email. Emails will be added to the queue by submitting the form. On cron run, emails will be dequeued.

src/Plugin/QueueWorker:

In that folder, create your QueueWorker file EmailQueue.php.

<?php
/**
 * @file
 * Contains \Drupal\mymodule\Plugin\QueueWorker\EmailQueue.
 */
namespace Drupal\Learning\Plugin\QueueWorker;
use Drupal\Core\Queue\QueueWorkerBase;
/**
 * Processes Tasks for Learning.
 *
 * @QueueWorker(
 *   id = "email_queue",
 *   title = @Translation("Learning task worker: email queue"),
 *   cron = {"time" = 60}
 * )
 */
class EmailQueue extends QueueWorkerBase {
  /**
   * {@inheritdoc}
   */
  public function processItem($data) {
    $mailManager = \Drupal::service('plugin.manager.mail');
    $params = $data;
    $mailManager->mail('learning', 'email_queue', $data['email'], 'en', $params , $send = TRUE);
  }
}

 

Your custom QueueWorker class must extend QueueWorkerBase and should implement processItem() method. The Email will be added to your email_queue

Creating forms for sending emails that contain email, subject, and message fields.

src/Form/FormQueue.php:

In this folder, create your email form FormQueue.php 

<?php
/**
 * @file
 * Contains \Drupal\Learning\Form\FormQueue.
 */

namespace Drupal\learning\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

/**
 * Contribute form.
 */
class FormQueue extends FormBase {
  /**
   * {@inheritdoc}
   */
  public function getFormId() {
     return 'queue_forms';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['email'] = array(
      '#type' => 'textfield',
      '#title' => t('Email'),
      '#required' => TRUE,
    );
    $form['subject'] = array(
      '#type' => 'textfield',
      '#title' => t('Subject'),
      '#required' => TRUE,
    );
    $form['message'] = array(
      '#type' => 'textarea',
      '#title' => t('Message'),
      '#required' => TRUE,
    );
    $form['submit'] = array(
      '#type' => 'submit',
      '#value' => t('Submit'),
    );
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    // Validate email
    if (!valid_email_address($form_state->getValues()['email'])) {
       $form_state->setErrorByName('Email', $this->t('Email address is not a valid one.'));
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $data['email'] = $form_state->getValues()['email'];
    $data['subject'] = $form_state->getValues()['subject'];
    $data['message'] = $form_state->getValues()['message'];
    $queue = \Drupal::queue('email_queue');
    $queue->createQueue();
    $queue->createItem($data);
  }
}
?>

In the submitForm(),  we are creating the Queue email_queue and adding the $data to the queue which contains the email, subject, and message.

/**
 * Implements hook_mail().
 */
function learning_mail($key, &$message, $params) {
  switch ($key) {
    // Send a simple message from the contact form.
    case 'email_queue':
      $message['subject'] = SafeMarkup::checkPlain($params['subject']);
      $message['body'][] = SafeMarkup::checkPlain($params['message']);
      break;
  }
}

In the Queue table, you can see the list of items added to the Queue.

pma

 

Get awesome tech content in your inbox