Batch example

    Let's say 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 is, to put it mildly, not the most correct solution.
    In this case, it is much more correct to implement this through batch .


    Using batch is extremely simple. Let me give you an example.

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


    There is also a certain function that works with this array.
    For example, we’ll just 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 elements 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 pass our array to batch_example_nodes_resave_batch () and see how everything works beautifully :)

    ps I apologize for the double post;

    Also popular now: