[Drupal] How to use Drupal queue in custom module?

| | 1 min read

The createItem() method lets you add data to the queue and the numberOfItems() method lets you see how many items are present in the queue. We use the claimItem() method of the queue object to get an item from the queue. claimItem() returns the data property, which contains whatever we put into the queue. If there is no item in the queue then claimItem() will return FALSE.

Steps for creating queue.

  • Create a Queue
  • Add item to the Queue-Put something into the queue for later.
  • Claim an item from the Queue - Get me the next Item that needs to be done.
  • Release the item from the Queue-Leave the item back in the queue because it couldn't be processed yet.
  • Remove the item from the Queue.
  • Count how many items are left in the Queue.

Methods used are:

  • createQueue() - Create a queue
  • createItem() - Add an item to the queue
  • claimItem() - Claim next queue item.
  • releaseItem() - Leave the item in the queue
  • deleteItem() - Delete the item from the queue.
  • numberOfItems() - Retrieve the number of items in the queue.

Example

    
    // Create queue object
    $queue = DrupalQueue::get('my_queue');
     
    // Create item
    $item = array(
      'dataitem1' => 'something',
      'int' => 123
    );
     
    // Add item to queue
    $queue­>createItem($item);
     
    // Report on number of items present
    echo $queue­>numberOfItems(); // Prints "1"
    while($item = $queue->claimItem()) {
    // Delete the item from queue.
        $queue->deleteItem($item);
    }