Tuesday, 1 July 2014

Basics of Apex Batch Class in Salesforce

What is batch class?

Batch class is just similar to Apex class except that batch class includes the Salesforce provide interface “Database.Batchable”.

Why we use batch class?

When we want to perform DML operations for bulk records or hit the web service then batch class comes in the picture.

Database.Batchable interface contains three method.
  • Start
  • Execute
  • Finish


Start Method

               global Database.QueryLocater start(Database.BatchableContext bc) {}

  • Use this method to get the records from database or object to be passed to “Execute” method.
  • This method returns Database.QueryLocater object that contains the records.
  • Query fired in the start method will return maximum 5,000,0000 records in a transaction.


Execute Method

           global void execute(Database.BatchableContext bc , List scope) {}


  • This method is used for do all the processing for data.
  • This method takes two arguments.
  • A reference of Database.BatchableContext object.
  • A list of sObject records.
  • The logical part of the code to process the data will be write in the execute method.


Finish Method

                global void finish(Database.BatchableContext bc) {}

  • This method takes only one argument a reference of Database.BatchableContext object.
  • This method is called when all the batches are processed.
  • This method is used for sending confirmation email to user or post-processing operations.


Here is the sample code

:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

global class batchAccountUpdate 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 + 'Updated';
         }
         update scope;
   }  

   global void finish(Database.BatchableContext BC) {
    }
}

:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::


How to execute/run batch class?

                   Id batchID = Database.executeBatch(new BatchClass() , Batch_Size);

  • This method is used for execute the Batch class.
  • This method returns the ID of the AsyncApexJob object.
  • This method takes two arguments.
  • An instance of the batch class
  • Batch size(Optional)
  • User can see the batch status or abort the batch anytime from the Apex Jobs.


How to schedule batch class ?

      Id schJobId = System.ScheduleBatch(new BatchClass() , ‘Job Name’ , Time_Interval , Batch_Size)

  • This method is used for schedule the batch job to run once in a specific time period in future.
  • This method will return the Scheduled Job Id(CronTrigger Id) click here for CRON.
  • This method takes four arguments                    
                              1. An instance of batch class
                              2. Job Name
                              3. Time Interval
                              4. Batch_Size(Optional)

  • To schedule batch class at a specific time scheduler class will be used.
  • Schedule class similar to Apex class except that it also includes Salesforce Provide Interface “Schedulable”.
  • Next, schedule the class either using Salesforce Apex page in user interface or using System.schedule method.


Why Database.Stateful ?

  • This is used for maintain the state across the transactions.
  • If you don’t specify the Database.Stateful, all Static and Instance member variables are set back to their original values.


Why Database.AllowCallouts ?

  • To use web service callouts in the batch apex, you must specify Database.AllowCallouts interface in the batch class definition.


Governor Limits for Batch Apex

  • Default batch size is 200.
  • Avoid SOQL queries inside for loop.
  • Maximum 5 batches can be run at a time in org.
  • Total number of sendEmail methods allowed per transaction is 10.
  • Total number of future methods allowed per transaction is 10.
  • Always use database methods like insert,update,upsert in the batch class.