Drupal 7 – Use queues for long running tasks in cron

Sometimes we may need to run some complex and time consuming tasks in Drupal cron but this may result in request timeout. It’s better to setup cron queues and run them in parallel requests.

Yesterday we have setup a hook_cron() task for batch updating nodes.
Drupal 7 – Batch update nodes by cron

Actually we can convert the tasks in the cron queues using hook_cron_queue_info() as follow.

function <MODULE>_cron() {
  // Get the nodes
  $sql = "SELECT nid FROM {node} WHERE type = :type";
  $result = db_query($sql, array(':type' => '<TYPE>'));
  // Setup the queue
  $queue = DrupalQueue::get('update_node');
  foreach ($result as $row) {
  // Create cache

function <MODULE>_cron_queue_info() {
  $queues['update_node'] = array(
    'worker callback' => 'update_node_callback',
    'time' => 15, // time in second for each worker
  return $queues;

function update_node_callback($data){
  $result = db_update('<FIELD TABLE NAME>')
    ->fields(array('<FIELD NAME>' => '<NEW VALUE>'))
    ->condition('entity_id', $data->nid)


Done =)

Reference: Drupal API – hook_cron_queue_info

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.