What is Batch Apex?

In this blog post, we will learn about Batch Apex.We use Batch Apex to build complex,long-running processes which operate on thousands of records. Batch apex divides record set into manageable batches to avoid hitting the governor limits.As you already know, salesforce has governor limits on data. But when you have to retrieve thousands of records or execute DML operation on thousands of records on object,it gets complex in salesforce and you have to deal with salesforce limits.
So in this case, Batch apex comes very handy. Using batch apex, we divide those record set into multiple batches. Each batch will be processed individually.

What is Batchable Interface?

In order to use Batch Apex, we must implement Database.Batchable interface. We have to implement below methods:
1)Start
2)Execute
3)Finish

Start: This method is called at the beginning of the batch apex job.This method will return either an object of type
Database.QueryLocator or an iterable that contains the records or objects passed to the job.This method will collect records on which the operation will be performed. These records are divided into batches and pass those to execute method.

Execute: this method contains the set of instructions which we want to perform on those records which we
retrieved from the Start method.

Finish: this method gets executed after all the batches are processed. We use this method to send email to inform them about the job completion.

To learn more:   https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_batch_interface.htm

 

global class AccountBatchUpdate implements Database.Batchable<sObject> {
 
global Database.QueryLocator start(Database.BatchableContext BC) {
String query = ‘SELECT Id,Name FROM Account’;
return Database.getQueryLocator(query);
}
 
global void execute(Database.BatchableContext BC, List<Account> scope) {
for(Account a : scope) {
a.Name = a.Name + ‘******’;
}
update scope;
}
 
global void finish(Database.BatchableContext BC) {
}
}
 
 
 

 

This Post Has 2 Comments

  1. Nice Deepika, Thanks for sharing it .

    U rock as always

  2. Thanks Deepika!!

Leave a Reply

Close Menu