Apex Batch class template

Batch classes are used to process very large volume of data without hitting Salesforce governor limits. Batch classes should implement "Database.Batchable" interface and it has three methods that must be implemented. 

Start

This method executes only once at the start of the batch. It queries all the records that needs to be processed and passes a Database.Querylocator or an iterable of objects to next execute method.

Execute

This method gets executed multiple times for one batch invocation. The total number of records that need to be processed from start method is divided into small chunks of batch size(default is 200) and for each chunk execute method is executed one after another. Since each of these chunks get separate execution context, you get separate governor limits for each chunk.

Finish

This method gets executed once at the end of the batch. ie after all individual execute chunks are complete. This is usually used for post processing activities like sending email notifying admin that batch executed successfully. 

Sample - Batch to update number of contacts to account


Common use cases for apex batch classes are below,


  1. Process bulk data that cannot be processed in single execution due to governor limits. For example making updates to more than 10k records.
  2. If regular execution is hitting heap limit, usually we need to go for batch/future class. Regular heap limit is 6MB. But in asynchronous execution methods like batch or future classes we get a 12MB heap limit
  3. Making thousands of callouts. Suppose you have to get some details about your accounts from an external system by hitting a webservice during night. You can make only 100 callouts in one transaction.  
  4. Send custom emails(with complex data from multiple objects which is not possible with workflow) to multiple people from apex. Keep batch size 10 as salesforce allows only 10 outbound emails in single transaction
  5. Make more than 10 Future callouts. Here also keep batch size as 10 because salesforce allows only 10 future callouts in one transaction.

No comments:

Post a Comment