In this blog, we will learn about Batch Apex in Salesforce with examples.
There are two types of apex in Salesforce:
Synchronous apex executes all processes in one go, requiring the user to wait for their completion.
The execution happens whenever the resources are available, It will run in a separate thread and it also provides an additional benefit of governor limits.
We have the following types of asynchronous apex:
- Future methods
- Queueable apex
- Batch Apex
- Scheduled Apex
What is Batch Apex in Salesforce?
The Batch class executes every transaction, by breaking down large sets of data into small chunks and 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 batch that is executing.
So, we can use Batch jobs for operations like data deletion, mass update, etc.
How to use Batch Apex?
To use Batch Apex, we have to implement the salesforce-provided interface Database.Batchable.
For monitoring the Batch Job we can go to Apex Jobs from the Quick Find box from the setup where we can monitor our jobs or stop the execution.
Database.Batchable Interface has three methods that we have to implement:
Every method in the Database.Batchable Interface will require a reference to Database.BatchableContext.
In this method, we collect the records of objects either with a Database.QueryLocator or Iterable to pass them into the execute method for operating.
By using Database.QueryLocator governor limit for the total number of records retrieved by SOQL queries is bypassed. If we use Iterable then limits will be enforced.
The start method will collect data and pass it into the Execute, which will then break it into chunks. This method will run multiple times according to the Batch size provided.
It takes an additional parameter, which will be the list of object data that we have collected in the start method.
This method will run after processing all the batches. However, we can use this to perform any post activities or send confirmation emails.
Let’s understand this by a simple example
If an Account object’s record is not active then update its related contact’s description to “Belongs to inactive account”.
The below snapshot is for the queried data. As of now we only have two contact records for that filter criteria, but a batch will be beneficial for a large set of records.
Apex Class (UpdateContactFields.apxc)
In the above snippet of the Apex class, firstly, we are querying the data in the start method. Secondly, in the execute method we have the scope parameter which is the list of data that we have collected in the start method.
Next, we are iterating over it. Hence it is of type sObject, we are typecasting it to the contact object and then performing the DML operation.
How to execute the Batch?
To execute the Batch we have to create the instance first, of our Batch class
UpdateContactFields then execute it by using DataBase.executeBatch.
Want to Learn Salesforce Flows? Checkout our Salesforce Flow Course
Note: The default batch size is 200 and the maximum batch size is 2000. We can also specify the batch size at the time of execution. If we don’t specify then batch will be executed with the default size.
In the developer console, Open the Execute Anonymous window then create the instance and click on Execute.
Here is the output generated: Description is updated to Belongs to Inactive Account.
We can also check the status of the Batch Class in Apex Job in the Quick Find box from setup.
Hence this batch job gets executed successfully, status is updated to Completed.
Following are the other statuses of Batch Job
- Holding – The job has been submitted and waiting for the resources to queue the job.
- Queued – Execution is pending.
- Preparing – After the execution of the start method, the status will last for a few minutes, depending on the size of the records.
- Processing – Execution has started.
- Aborted – If we abort the job manually then this status will get updated.
- Completed – If the job is completed whether with or without fail.
- Failures – If the job went into some system failure. (any governor limit or any other limitations.
What are the limitations of Batch Apex?
- Database.QueryLocator can return up to 50 million records, if it passes more than 50 million, then it terminates and marks the job as a failure.
- We can queue a maximum of 5 jobs or in other words 5 jobs can be active at the same time.
- The maximum batch size is 2000 so if we pass more than that it will break into smaller chunks.
- The org can run only one Batch job’s start method at the same time.
What are the best practices for Batch Apex?
- The implementation method of the Database.Batchable interface must be defined as public or global.
- If more than 2000 requests are in the queue, other requests will be delayed. As a best practice try to reduce the batch size.
- Furthermore, avoid using related subqueries, as they can slow down the execution speed of the batch.
- Also, the Batch class can’t call the method declared with a future annotation.
- Batch Apex jobs perform more efficiently when the start method generates a QueryLocator object without incorporating related records using subqueries.
1. What is the Apex Flex queue?
Batch Jobs that are in holding status go into the flex queue. We can also reorder our batch jobs. To navigate to the Apex Flex queue, go to setup and then the Quick Find box.
2. Can we schedule the Batch Apex?
Yes, we can schedule the batch apex by using System.scheduleBatch
Here, bactchObj is the instance, schedule batch example is the job name, and 60 is minutes which means batch gets executed in 60 minutes from now.
Also, it will return the Job Id that we can use to monitor, abort, etc. our Batch Job.
Batch Apex is a great tool for Salesforce developers to efficiently process large datasets and perform complex operations.