Salesforce uses governor limits to ensure efficient resources in a multi-tenant environment. Asynchronous apex helps handle the governor limits in a multi-tenant architecture. We have batch Apex types in asynchronous processes in Salesforce Apex.
In this tutorial, we will learn about Batch Apex in Salesforce, using examples. In that, I will explain what Batch Apex is in Salesforce, its methods, and how to use a Batch Apex in Salesforce.
What is Batch Apex in Salesforce?
The batch class executes every transaction by breaking down large datasets into small blocks or batches, providing us with the additional benefit of a governor limit.
Every batch in the batch apex runs with the new set of governor limits. In other words, the governor limit will reset for every executing batch.
The batch apex implements the Database.Batchable interface provides enhanced control over record processing compared to the standard synchronous Apex.
How to Use Batch Apex in Salesforce?
To use batch Apex, we must implement the Salesforce-provided interface Database.Batchable.
To monitor the batch Job, we can go to Apex Jobs in the Quick Find box in the setup. There, we can monitor our jobs or stop their execution. Database.Batchable Interface has three methods that we have to implement
Important Methods of Batch Apex in Salesforce
The following are three important methods in batch apex in Salesforce.
Start() Method in Batch Apex:
In the start() method of batch apex, we collect the records of objects with a Database.QueryLocator and pass them into the execute method for the operation.
Syntax of Start() Method:
public Database.QueryLocator start( Database.BatchableContext BC ){ }
Database.QueryLocator is used in batch Apex to retrieve records. This bypasses the usual governor limit of 50,000 records for SOQL queries.
Execute() Method in Batch Apex:
The start method collects data and passes it to the execute() method, which breaks it into batches. This method runs multiple times according to the provided batch size.
Syntax of Execute() Method:
public void execute( Database.BatchableContext BC, list<P>){ }
It takes an additional parameter, which will be the list collection of object records that we have collected in the start method.
Finish() Method in Batch Apex:
This method will run after processing all the batches, and it is also optional. However, we can use it to perform any post-processing activities, such as displaying a success message, sending email notifications, logging batch completion, and triggering another batch job.