fbpx

Free Salesforce Developers Tutorials >

Chapter 12 - Governor Limits and Batch Apex >

Batch Class in Apex

Batch Class in Apex

What You’ll Learn


S2 Labs

What is Batch Class in Apex?

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.

Batch Apex is exposed as an interface that must be implemented by the developer. Batch jobs can be programmatically invoked at runtime using Apex.

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.

But 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 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).

Batch Class Methods

Database. Batchable interface contains 3 methods that must be implemented:

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.

2. execute() :

To do the required processing of 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.

3. finish() :

To send confirmation emails or execute post-processing operations, we use finish(). This method is called after all batches are processed.

Note:

The order of execution of batches is not guaranteed.

Example Of Batch Class In Apex

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<sObject>) 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<Account> 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’));

Download Study Material

Get access to exclusive study material for Salesforce Certification and ace your exams!

Download Now

Our Salesforce Certification Courses

Hey there! Glad you made it through our Salesforce Developer Training for beginners . But wait! We've got some high-in-demand Salesforce courses for you to take your Salesforce skills to the next level, making you a desired professional in the Salesforce job market.

Post a Comment

Your email address will not be published. Required fields are marked *