Saturday, May 15, 2021

How to control number of batches in batch apex using scope size?

As we know, the default scope size is 200. If no size is specified with the optional scope parameter of Database.executeBatch, Salesforce chunks the records returned by the start method into batches of 200 records. The optional scope parameter of Database.executeBatch can have a maximum value of 2,000.

When an apex job is executed by setting some value for scope size, it is not necessary that the number of records processed in one batch iteration be the same as the scope size specified.

Records from the query locator are retrieved in chunks of the given chunk size, called retrieveChunkSize.

Chunk sizes available are 100, 400, and 2000.

The selection of chunk size depends on the scope size specified.

If 1 <= scopeSize <= 100, then retrieveChunkSize = 100.

If 101 <= scopeSize <= 400, then retrieveChunkSize = 400.

If 401 <= scopeSize <= 2000, then retrieveChunkSize = 2000.

So let's say we have 285 records to be processed and we specify the scope size as 80, then the retrieveChunkSize will be 100.

In this case, the total number of batches will not be 4, i.e., (285/80), but in this case, it would be 3 retrieve chunks and 6 execute chunks, so the total number of batches will be 6.

1. Retrieve chunk 1: retrieve the first 100 records 

Execute chunk 1: pass the first 80 records to the execute() method.

Execute chunk 2: pass the remaining 20 records from this retrieve chunk to the execute() method.

2. Retrieve chunk 2: retrieve the next 100 records.

Execute chunk 3: pass the first 80 records to the execute() method.

Execute chunk 4: pass the remaining 20 records from this retrieve chunk to the execute() method.

3. Retrieve chunk 3: retrieve the next 85 records.

Execute chunk 5: pass the first 80 records to the execute() method.

Execute chunk 6: pass the remaining 5 records from this retrieve chunk to the execute() method.


No comments:

Post a Comment