Hook_post_update executes an update which is intended to update data, like entities.
These updates are executed after all hook_update_N() implementations. At this stage Drupal is already fully repaired so you can use any API as you wish.
Updating node titles with post update hook
In this example we will take a look on how to update title of an existing nodes with post update hook in batches.
We will start by creating .post_update.php file inside our module root folder.
Inside we will place our post_update hook function and replace NAME with an arbitrary machine name.
Alphanumeric order of the NAME ensures the executing order of update. If update order is mandatory, you should add numerical prefix to
NAMEor make it completely numerical.
Post_update file
File: .../your_module/your_module.post_update.php
"Setup"
First we need to gather all nodes that we want to update. In this example all nodes of type event.
To use batches we need to set the total number of nodes and current count of node which will be incremented for each processed node.
Gathering data
Next we need to set the limit for 1 batch and gather nodes for our batch. In this case we can use query range.
In this example we are using simple service which takes the string and returns it in title case.
Processing data
After we have our data set for one batch, we process it.
It is important to increment $sandbox['current'] as this will be the starting value for next batches query range.
Finishing the operation
Batch operation will be finished when $sandbox['#finished'] = 1.
Best way is to set $sandbox['#finished'] to a value between 0 and 1 to indicate the percent completed.
Alternatives
As an alternative of using query range to gather data it can be gathered in the "setup".
Note: It is important to gather data, for example reading from file inside IF statement as this part of the code is run only once and not once per batch.
and then process it in batches