Batch Apex Salesforce With Example

batch Apex Salesforce

What is Batch Apex? – Batch Apex is a way to break down a Job  into multiple smaller batches of manageable jobs which are processed separately. It is a Interface which the developer can implement and call pragmatically at run time.
**NoteNot more 5 queued or Active Batch Jobs can be there at a time.

What is the Use of Batch Apex ? Several Apex Governor limits can be conquered using batch apex as it break downs a Job in smaller jobs. It is useful when you require to query thousand of records and perform DML operations on them without hitting the governor limits.

Example :- Suppose you organization has millions of Accounts and you want to update them.
Issues without Batch Apex:  How to query records more than 50000 ?
How to perform DML on more than 10000 records?

Lets now see how we overcome it using Batch Apex.
Batch Apex will break down this task into smaller jobs and process them seperately to avoid hitting governor limits. Batch Apex Implements the “Database.Batchable” Interface which has 3 methods.
1. Start
2. execute
3. Finish
  • Start method is First method called automatically when the batch job is invoked. It generates the set of records on which the operation has to be performed and sends it to Execute method in smaller chunks.
  • Execute Method performs operation which we want to perform on the records fetched from start method.
  • Finish method is called after processing all the batches in execute method.

Sample Code to Update all Account records using Batch Apex

global class AccountUpdatebatch implements Database.Batchable<sObject> {
    global Database.QueryLocator start(Database.BatchableContext BC) {
        String query = 'SELECT Name FROM Account';
        return Database.getQueryLocator(query);
    }
   
global void execute(Database.BatchableContext BC, List<Account> scope) {
        //Scope comes from start in batches of 200
         for(Account acc : scope)
         {
            // Write the Operation logic you want to perform here,
            // For example  I have appended Updated with the account names.
            acc.Name = acc.Name + '-Updated';  
            
         }
         update scope;
    }   
    
    global void finish(Database.BatchableContext BC) {
     // Write the Operation logic you want to perform after all Batches are processed.
      }
}
To Run the Batch Apex :  Go to console and run the below mentioned code snippet .

AccountUpdatebatch bat= new AccountUpdatebatch ();
database.executebatch(bat);
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s