batch_example.module

Tracking 8.x-1.x branch
  1. drupal
    1. 6 contributions/examples/batch_example/batch_example.module
    2. 7 contributions/examples/batch_example/batch_example.module
    3. 8 contributions/examples/batch_example/batch_example.module

Outlines how a module can use the Batch API.

Functions & methods

NameDescription
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_simple_form_submit
_batch_example_get_http_requests
_batch_example_update_http_requestsUtility function to count the HTTP requests in a session variable.

File

View source
  1. <?php
  2. /**
  3. * @file
  4. * Outlines how a module can use the Batch API.
  5. */
  6. /**
  7. * @defgroup batch_example Example: Batch API
  8. * @ingroup examples
  9. * @{
  10. * Outlines how a module can use the Batch API.
  11. *
  12. * Batches allow heavy processing to be spread out over several page
  13. * requests, ensuring that the processing does not get interrupted
  14. * because of a PHP timeout, while allowing the user to receive feedback
  15. * on the progress of the ongoing operations. It also can prevent out of memory
  16. * situations.
  17. *
  18. * The @link batch_example.install .install file @endlink also shows how the
  19. * Batch API can be used to handle long-running hook_update_N() functions.
  20. *
  21. * Two harmless batches are defined:
  22. * - batch 1: Load the node with the lowest nid 100 times.
  23. * - batch 2: Load all nodes, 20 times and uses a progressive op, loading nodes
  24. * by groups of 5.
  25. * @see batch
  26. */
  27. /**
  28. * Implements hook_menu().
  29. */
  30. function batch_example_menu() {
  31. $items = array();
  32. $items['examples/batch_example'] = array(
  33. 'title' => 'Batch example',
  34. 'description' => 'Example of Drupal batch processing',
  35. 'page callback' => 'drupal_get_form',
  36. 'page arguments' => array('batch_example_simple_form'),
  37. 'access callback' => TRUE,
  38. );
  39. return $items;
  40. }
  41. /**
  42. * Form builder function to allow choice of which batch to run.
  43. */
  44. function batch_example_simple_form() {
  45. $form['description'] = array(
  46. '#type' => 'markup',
  47. '#markup' => t('This example offers two different batches. The first does 1000 identical operations, each completed in on run; the second does 20 operations, but each takes more than one run to operate if there are more than 5 nodes.'),
  48. );
  49. $form['batch'] = array(
  50. '#type' => 'select',
  51. '#title' => 'Choose batch',
  52. '#options' => array(
  53. 'batch_1' => t('batch 1 - 1000 operations, each loading the same node'),
  54. 'batch_2' => t('batch 2 - 20 operations. each one loads all nodes 5 at a time'),
  55. ),
  56. );
  57. $form['submit'] = array(
  58. '#type' => 'submit',
  59. '#value' => 'Go',
  60. );
  61. // If no nodes, prevent submission.
  62. // Find out if we have a node to work with. Otherwise it won't work.
  63. $nid = batch_example_lowest_nid();
  64. if (empty($nid)) {
  65. drupal_set_message(t("You don't currently have any nodes, and this example requires a node to work with. As a result, this form is disabled."));
  66. $form['submit']['#disabled'] = TRUE;
  67. }
  68. return $form;
  69. }
  70. function batch_example_simple_form_submit($form, &$form_state) {
  71. $function = 'batch_example_' . $form_state['values']['batch'];
  72. $_SESSION['http_request_count'] = 0; // reset counter for debug information.
  73. // Execute the function named batch_example_1 or batch_example_2.
  74. $batch = $function();
  75. batch_set($batch);
  76. }
  77. /**
  78. * Batch 1 definition: Load the node with the lowest nid 1000 times.
  79. * This creates an operations array defining what batch 1 should do, including
  80. * what it should do when it's finished. In this case, each operation is the
  81. * same and by chance even has the same $nid to operate on, but we could have
  82. * a mix of different types of operations in the operations array.
  83. */
  84. function batch_example_batch_1() {
  85. $nid = batch_example_lowest_nid();
  86. $num_operations = 1000;
  87. drupal_set_message(t('Creating an array of @num operations', array('@num' => $num_operations)));
  88. $operations = array();
  89. // Set up an operations array with 1000 elements, each doing function
  90. // batch_example_op_1.
  91. // Each operation in the operations array means at least one new HTTP request,
  92. // running Drupal from scratch to accomplish the operation. If the operation
  93. // returns with $context['finished'] != TRUE, then it will be called again.
  94. // In this example, $context['finished'] is always TRUE.
  95. for ($i = 0; $i<$num_operations; $i++) {
  96. // Each operation is an array consisting of
  97. // - the function to call
  98. // - An array of arguments to that function
  99. $operations[] = array('batch_example_op_1', array($nid, t('(Operation @operation)', array('@operation' => $i))));
  100. }
  101. $batch = array(
  102. 'operations' => $operations,
  103. 'finished' => 'batch_example_finished',
  104. );
  105. return $batch;
  106. }
  107. /**
  108. * Batch operation for batch 1: load a node.
  109. * This is the function that is called on each operation in batch 1.
  110. */
  111. function batch_example_op_1($nid, $operation_details, &$context) {
  112. $node = node_load($nid, NULL, TRUE);
  113. // Store some result for post-processing in the finished callback.
  114. $context['results'][] = $node->nid . ' : ' . check_plain($node->title);
  115. // Optional message displayed under the progressbar.
  116. $context['message'] = t('Loading node "@title"', array('@title' => $node->title)) . ' ' . $operation_details;
  117. _batch_example_update_http_requests();
  118. }
  119. /**
  120. * Batch 2 : Prepare a batch definition that will load all nodes 20 times.
  121. */
  122. function batch_example_batch_2() {
  123. $num_operations = 20;
  124. // Give helpful information about how many nodes are being operated on.
  125. $node_count = db_query('SELECT COUNT(DISTINCT nid) FROM {node}')->fetchField();
  126. drupal_set_message(t('There are @node_count nodes so each of the @num operations will require @count HTTP requests.', array('@node_count' => $node_count, '@num' => $num_operations, '@count' => ceil($node_count / 5))));
  127. $operations = array();
  128. // 20 operations, each one loads all nodes.
  129. for ($i = 0; $i < $num_operations; $i++) {
  130. $operations[] = array('batch_example_op_2', array(t('(Operation @operation)', array('@operation' => $i))));
  131. }
  132. $batch = array(
  133. 'operations' => $operations,
  134. 'finished' => 'batch_example_finished',
  135. // We can define custom messages instead of the default ones.
  136. 'title' => t('Processing batch 2'),
  137. 'init_message' => t('Batch 2 is starting.'),
  138. 'progress_message' => t('Processed @current out of @total.'),
  139. 'error_message' => t('Batch 2 has encountered an error.'),
  140. );
  141. return $batch;
  142. }
  143. /**
  144. * Batch operation for batch 2 : load all nodes, 5 by five
  145. * After each group of 5 control is returned to the batch API for later
  146. * continuation.
  147. */
  148. function batch_example_op_2($operation_details, &$context) {
  149. // Use the $context['sandbox'] at your convenience to store the
  150. // information needed to track progression between successive calls.
  151. if (empty($context['sandbox'])) {
  152. $context['sandbox'] = array();
  153. $context['sandbox']['progress'] = 0;
  154. $context['sandbox']['current_node'] = 0;
  155. // Save node count for the termination message.
  156. $context['sandbox']['max'] = db_query('SELECT COUNT(DISTINCT nid) FROM {node}')->fetchField();
  157. }
  158. // Process nodes by groups of 5 (arbitrary value).
  159. // When a group of five is processed, the batch update engine determines
  160. // whether it should continue processing in the same request or provide
  161. // progress feedback to the user and wait for the next request.
  162. // That way even though we're already processing at the operation level
  163. // the operation itself is interruptible.
  164. $limit = 5;
  165. // Retrieve the next group of nids.
  166. $result = db_select('node', 'n')
  167. ->fields('n', array('nid'))
  168. ->orderBy('n.nid', 'ASC')
  169. ->where('n.nid > :nid', array(':nid' => $context['sandbox']['current_node']))
  170. ->extend('PagerDefault')
  171. ->limit($limit)
  172. ->execute();
  173. foreach ($result as $row) {
  174. // Here we actually perform our dummy 'processing' on the current node.
  175. $node = node_load($row->nid, NULL, TRUE);
  176. // Store some result for post-processing in the finished callback.
  177. $context['results'][] = $node->nid . ' : ' . check_plain($node->title) . ' ' . $operation_details;
  178. // Update our progress information.
  179. $context['sandbox']['progress']++;
  180. $context['sandbox']['current_node'] = $node->nid;
  181. $context['message'] = check_plain($node->title);
  182. }
  183. // Inform the batch engine that we are not finished,
  184. // and provide an estimation of the completion level we reached.
  185. if ($context['sandbox']['progress'] != $context['sandbox']['max']) {
  186. $context['finished'] = ($context['sandbox']['progress'] >= $context['sandbox']['max']);
  187. }
  188. _batch_example_update_http_requests();
  189. }
  190. /**
  191. * Batch 'finished' callback used by both batch 1 and batch 2.
  192. */
  193. function batch_example_finished($success, $results, $operations) {
  194. if ($success) {
  195. // Here we could do something meaningful with the results.
  196. // We just display the number of nodes we processed...
  197. drupal_set_message(t('@count results processed in @requests HTTP requests.', array('@count' => count($results), '@requests' => _batch_example_get_http_requests())));
  198. drupal_set_message(t('The final result was "%final"', array('%final' => end($results))));
  199. }
  200. else {
  201. // An error occurred.
  202. // $operations contains the operations that remained unprocessed.
  203. $error_operation = reset($operations);
  204. drupal_set_message(t('An error occurred while processing @operation with arguments : @args', array('@operation' => $error_operation[0], '@args' => print_r($error_operation[0], TRUE))));
  205. }
  206. }
  207. /**
  208. * Utility function - simply queries and loads the lowest nid.
  209. * @return A nid or NULL if there are no nodes.
  210. */
  211. function batch_example_lowest_nid() {
  212. $select = db_select('node', 'n')
  213. ->fields('n', array('nid'))
  214. ->orderBy('n.nid', 'ASC')
  215. ->extend('PagerDefault')
  216. ->limit(1);
  217. $nid = $select->execute()->fetchField();
  218. return $nid;
  219. }
  220. /**
  221. * @} End of "defgroup batch_definitions".
  222. */
  223. /**
  224. * Utility function to count the HTTP requests in a session variable.
  225. */
  226. function _batch_example_update_http_requests() {
  227. $_SESSION['http_request_count']++;
  228. }
  229. function _batch_example_get_http_requests() {
  230. return !empty($_SESSION['http_request_count']) ? $_SESSION['http_request_count'] : 0;
  231. }
  232. /**
  233. * @} End of "defgroup batch_example".
  234. */