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) {
$queue->createItem($row);
}
// Create cache
drupal_flush_all_caches();
}
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)
->execute();
}
Done =)
Reference: Drupal API – hook_cron_queue_info
