12

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 enforces a limitation on the number of records you can query or process in one transaction to ensure the performance of the platform. This limitation, which is called Salesforce Governor Limits, would, therefore, present a problem if we needed to go through 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 goes through all Accounts and Opportunities on a nightly basis and updates them, 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 number of records in a batch (default is 200 records).
  • Asynchronous Processing: The jobs run in the background with minimal interference with other activities.
  • Retry on Failure: You have the option to resubmit either all failed records or specific failed records.

Batch Class Methods

Basically, Batch Apex is defining an Apex 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(). 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 of Batch Apex

As we know, the salesforce governor limits its data. 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 enterprises, it is essential to manage thousands of records every day. Adding/editing/deleting them when needed.

Salesforce has come up with 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 apex class that extends the Database. Batchable Interface because of which the salesforce compiler will know, this class incorporates batch jobs. Below is a sample class that is designed to delete all the records of the Account object (Let’s say your organization contains more than 50 thousand records, and you want to mass delete all of them).

global class DeleteAccounts implements Database.Batchable {
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 | Iterable) start(Database.BatchableContext bc) {
return Database.getQueryLocator(query); // can fetch up-to 50 Million records
}
// deleting the received chunk of records
global void execute(Database.BatchableContext bc, List 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 batch instanceid = 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.

ServiceNow Stripe