You are here

function batch_example_op_2 in Examples for Developers 3.x

Same name and namespace in other branches
  1. 8 batch_example/batch_example.module \batch_example_op_2()
  2. 6 batch_example/batch_example.module \batch_example_op_2()
  3. 7 batch_example/batch_example.module \batch_example_op_2()

Batch operation for batch 2: five at a time.

This is the function that is called on each operation in batch 2.

After each group of 5 control is returned to the batch API for later continuation.

Related topics

1 string reference to 'batch_example_op_2'
BatchExampleForm::generateBatch2 in modules/batch_example/src/Form/BatchExampleForm.php
Generate Batch 2.

File

modules/batch_example/batch_example.module, line 59
Outlines how a module can use the Batch API.

Code

function batch_example_op_2($operation_details, &$context) {

  // Use the $context['sandbox'] at your convenience to store the
  // information needed to track progression between successive calls.
  if (empty($context['sandbox'])) {
    $context['sandbox'] = [];
    $context['sandbox']['progress'] = 0;
    $context['sandbox']['current_node'] = 0;

    // Save node count for the termination message.
    $context['sandbox']['max'] = 30;
  }

  // Process in groups of 5 (arbitrary value).
  // When a group of five is processed, the batch update engine determines
  // whether it should continue processing in the same request or provide
  // progress feedback to the user and wait for the next request.
  // That way even though we're already processing at the operation level
  // the operation itself is interruptible.
  $limit = 5;

  // Retrieve the next group.
  $result = range($context['sandbox']['current_node'] + 1, $context['sandbox']['current_node'] + 1 + $limit);
  foreach ($result as $row) {

    // Here we actually perform our dummy 'processing' on the current node.
    usleep(20000);

    // Store some results for post-processing in the 'finished' callback.
    // The contents of 'results' will be available as $results in the
    // 'finished' function (in this example, batch_example_finished()).
    $context['results'][] = $row . ' ' . $operation_details;

    // Update our progress information.
    $context['sandbox']['progress']++;
    $context['sandbox']['current_node'] = $row;
    $context['message'] = t('Running Batch "@id" @details', [
      '@id' => $row,
      '@details' => $operation_details,
    ]);
  }

  // Inform the batch engine that we are not finished,
  // and provide an estimation of the completion level we reached.
  if ($context['sandbox']['progress'] != $context['sandbox']['max']) {
    $context['finished'] = $context['sandbox']['progress'] >= $context['sandbox']['max'];
  }
}