Example: Batch API

  1. drupal
    1. 8
    2. 6
    3. 7

Outlines how a module can use the Batch API.

Batches allow heavy processing to be spread out over several page requests, ensuring that the processing does not get interrupted because of a PHP timeout, while allowing the user to receive feedback on the progress of the ongoing operations. It also can prevent out of memory situations.

The .install file also shows how the Batch API can be used to handle long-running hook_update_N() functions.

Two harmless batches are defined:

  • batch 1: Load the node with the lowest nid 100 times.
  • batch 2: Load all nodes, 20 times and uses a progressive op, loading nodes by groups of 5.

See also


Functions & methods

batch_example_batch_1Batch 1 definition: Load the node with the lowest nid 1000 times. This creates an operations array defining what batch 1 should do, including what it should do when it's finished. In this case, each operation is the same and by chance even has…
batch_example_batch_2Batch 2 : Prepare a batch definition that will load all nodes 20 times.
batch_example_finishedBatch 'finished' callback used by both batch 1 and batch 2.
batch_example_lowest_nidUtility function - simply queries and loads the lowest nid.
batch_example_menuImplements hook_menu().
batch_example_op_1Batch operation for batch 1: load a node. This is the function that is called on each operation in batch 1.
batch_example_op_2Batch operation for batch 2 : load all nodes, 5 by five After each group of 5 control is returned to the batch API for later continuation.
batch_example_simple_formForm builder function to allow choice of which batch to run.
batch_example_update_7100Example of batch-driven update function.

examples/batch_example/batch_example.module, line 8