2 min read

Running Batch operations via cron in Drupal 7

Many users are familiar with Drupal’s powerful Batch API. Batch operations allow manipulation of a large amount of data simultaneously. They are used, for example, in translation updates and bulk operations.

To run batch operations in the background via cron:

function MY_MODULE_cron() {
  // Batch operation function, any name.
  MY_MODULE_unprogressive_batch();
}

function MY_MODULE_unprogressive_batch() {
  $operations = array();
  $objects = array();

  // After populating $objects array.
  foreach ($objects as $row) {
    $operations[] = array('MY_MODULE_some_operation', array($row));
  }
  $batch = array(
    'operations' => $operations,
    'title' => t('Processing'),
    'init_message' => t('Initializing.'),
    'progress_message' => t('Completed @current of @total.'),
    'error_message' => t('An error has occurred.'),
  );

  // Set batch.
  batch_set($batch);

  // The following part is for running batch from cron in the background.
  $batch = &batch_get();
  $batch['progressive'] = FALSE;
  batch_process();
  return TRUE;
}

function MY_MODULE_some_operation($row) {
  // Perform operations.
}

Example of how to run a second batch from the finished callback of the first (without cron):

function MY_MODULE_batch_finished_callback($success, $results, $operations) {
  // Here build new operations.
  $operations = array();

  if (count($operations) > 0) {
    // Clear static $batch array to run new batch.
    $batch =& batch_get();
    $batch = array();
    $batch_definition = array(
      'operations' => $operations,
      'title' => t('Processing'),
      'init_message' => t('Starting process'),
      'progress_message' => '',
      'error_message' => t('An error occurred. Some or all of the import processing has failed.'),
      'finished' => 'module_batch_finished_callback',
    );
    batch_set($batch_definition);
    
    // Redirect after finished, if necessary.
    batch_process('');
  }
}