📜 ⬆️ ⬇️

Batch Usage Example

Suppose you need to do some operation with a large number of node and the script execution time is not enough.
In this case, you can increase the execution time of the script as follows:
set_time_limit ($ time); // $ time in seconds

This, to put it mildly, is not the right decision.
In this case, it is much more correct to implement this via batch .


Using batch is extremely simple. Now give an example.

Suppose we have an array of nid:
Copy Source | Copy HTML $nids = array ( 0 => nid, 1 => nid, … n => nid, );
  1. Copy Source | Copy HTML $nids = array ( 0 => nid, 1 => nid, … n => nid, );
  2. Copy Source | Copy HTML $nids = array ( 0 => nid, 1 => nid, … n => nid, );
  3. Copy Source | Copy HTML $nids = array ( 0 => nid, 1 => nid, … n => nid, );
  4. Copy Source | Copy HTML $nids = array ( 0 => nid, 1 => nid, … n => nid, );
  5. Copy Source | Copy HTML $nids = array ( 0 => nid, 1 => nid, … n => nid, );
  6. Copy Source | Copy HTML $nids = array ( 0 => nid, 1 => nid, … n => nid, );

')
There is also a function that works with this array.
For example, we will simply load and save the node.

Copy Source | Copy HTML
  1. function batch_example_nodes_resave ( $ nids = array ()) {
  2. foreach ( $ nids as $ nid ) {
  3. if (is_numeric ( $ nid )) {
  4. $ node = node_load ( $ nid );
  5. node_save ( $ node );
  6. }
  7. }
  8. }


Now we describe the function with batch.
We will divide the $ nids array into parts (5 ellements each) and send to batch_example_nodes_resave ()

Copy Source | Copy HTML
  1. function batch_example_nodes_resave_batch ( $ nids = array ()) {
  2. $ operations = array ();
  3. while ( $ nids ) {
  4. $ nids_part = array_splice ( $ nids , 0 , 5 );
  5. $ operations [] = array ( 'batch_example_nodes_resave' , array ( $ nids_part ));
  6. }
  7. $ batch = array (
  8. 'title' => t ( 'Resave nodes' ),
  9. 'operations' => $ operations ,
  10. );
  11. batch_set ( $ batch );
  12. batch_process ();
  13. }


Now it's enough to transfer our array to batch_example_nodes_resave_batch () and see how everything works beautifully :)

ps I apologize for the double post, Habr Ceto feels not important at all ...

Source: https://habr.com/ru/post/132020/


All Articles