Batch Class in Apex
What is Batch Apex in Salesforce?
Batch Apex is used to process large record sets asynchronously in Salesforce. By default, Salesforce imposes a limit on the number of records you can query or process in a single transaction to ensure platform performance. This limitation, called Salesforce Governor Limits, would therefore pose a problem if we needed to process thousands or millions of records.
Batch Apex splits these large jobs into smaller “batches” of records, processing each batch separately. This approach ensures that your code stays within Salesforce’s governor limits while handling high-volume tasks effectively.
Batch Apex operates over small batches of records, covering your entire record set and breaking the processing down into manageable chunks. We could build a data-cleansing operation that runs nightly to update all Accounts and Opportunities, if necessary, based on custom criteria.
It is exposed as an interface that the developer must implement. Batch jobs can be programmatically invoked at runtime using Apex.
Key Features of Batch Apex
- Processes Large Data Sets: Processes records beyond the common governor limits.
- Flexible batching: Allow developers to set the batch size (default: 200 records).
- Asynchronous Processing: The jobs run in the background with minimal interference with other activities.
- Retry on Failure: You can resubmit either all failed records or specific ones.
Batch Class Methods
Basically, a batch class in Apex is a class that implements the Database.Batchable interface. The interface provides a person with three main methods:
1. start() :
It collects the records or objects to pass to the interface method execute(), call the start() at the beginning of a BatchApexJob. This method returns either a Database.QueryLocator object that contains the records passed to the job.
- Prepare the batch job to determine what records are going to be processed
- Returns a Database.QueryLocator or a list of records to process.
2. execute() :
To process each chunk of data, use the execute method. This method is called for each batch of records that you pass to it. This method takes a reference to the Database.BatchableContext object.
- Runs for each batch of data, containing the logic to process records.
- Processes a specific number of records (batch size), reducing the load on system resources.
3. finish() :
To send confirmation emails or execute post-processing operations, we use finish(). Common use cases include sending summary emails, logging results, updating records, or chaining another Batch Apex job. This method is called after all batches are processed.
- Executes after all batches are processed.
- Useful for finalizing tasks, such as sending notifications or logging results.
Note: The execution order of batches is not guaranteed.
Need for Batch Apex
As we know, Salesforce limits the amount of data it stores. When you want to fetch thousands of records or fire DML on thousands of rows of objects, it is very complex in Salesforce, and it does not allow you to operate on more than a certain number of records, which satisfies the Governor’s limits.
However, for medium- to large-sized enterprises, managing thousands of records every day is essential. Adding/editing/deleting them when needed.
The Salesforce batch processing is supported by a powerful concept called Batch Apex. Batch Apex allows you to handle more records and manipulate them by using a specific syntax.
We have to create a global batch class in Apex that extends the Database.Batchable Interface, because of which the Salesforce compiler will know that this class incorporates batch jobs. Below is a sample class designed to delete all records of the Account object (Let’s say your organization contains more than 50,000 records, and you want to mass-delete them).
A batch apex example:
global class DeleteAccounts implements Database.Batchable<SObject> {
String query;
// Assigning query string to global variable
public DeleteAccounts(String queryStr) {
query = queryStr;
}
// collect the batches of records or objects to be passed to execute
global Database.QueryLocator start(Database.BatchableContext bc) {
return Database.getQueryLocator(query);
}
return Database.getQueryLocator(query); // can fetch up-to 50 Million records
}
// deleting the received chunk of records
global void execute(Database.BatchableContext bc, List<SObject> accList) {
try {
// deleting the Account Records
delete accList;
} catch(Exception e) {
System.debug(e);
}
}
// Send an email to the User after your batch completes
global void finish(Database.BatchableContext BC)
{
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage(); String[]
toAddresses = new String[] {‘[email protected]’}; mail.setToAddresses(toAddresses);
mail.setSubject(‘Apex Batch Job is done‘);
mail.setPlainTextBody(‘The batch Apex job processed ‘);
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail }); }
}
// This is how the batch class is called.
Id batchInstanceId = Database.executeBatch(new DeleteAccounts('SELECT Id FROM Account'));
Next Topic
Need more support?
Get a head start with our FREE study notes!
Learn more and get all the answers you need at zero cost. Improve your skills using our detailed notes prepared by industry experts to help you excel.