[Drupal] Batch API in Drupal

By fathimath.sajila | 06th October 2016 | 1 min read

To process very large data is very much time-consuming, it may lead to PHP timeout error. To process very large data, Drupal offers a batch API. The Batch API allows you to run one or more operations on a large set of data without timeout and feedback on the progress of the operation.

Advantage of Batch API:

  • Avoid PHP timeout.
  • Display the progress of the process.
  • Avoid out of memory situations.

Let's look a simple example in Drupal 6 that use batch API:


function mymodule_menu() {
  $items = array();
  $items['mymodule/batch-example'] = array(
    'title' => 'Batch',
    'page callback' => 'batch_process',
  );
  return $items;
}

function mymodule_batch() {
  $results = db_query('SELECT nid FROM {node} ORDER BY nid ASC LIMIT 50');
  $operations = array();
  while ($data = db_fetch_object($results)) {
    $operations[] = array('example_batch', array($data->nid));
  }
  $batch = array(
    'operations' => $operations,
    'finished' => 'example_batch_finished',
  );
  batch_set($batch);
  batch_process('user');
}

function example_batch($nid, &$context) {
  $node = node_load($nid);
  // Do some stuff here to make changes...
  $context['message'] = t('Processing operations @title', array('@title' => $node->title));
}

function example_batch_finished($success, $results, $operations) {
  if ($success) {
    $message = count($results) . ' processed.';
  }
  else {

    $error_operation = reset($operations);
    $message = 'An error occurred ' . $error_operation[0];
  }
  drupal_set_message($message);
}

Hope the above helps. Please feel free to get in touch with us for any queries.