Batch Apex Salesforce

Your class must implement the Database.Batchable interface and include the following three methods so it becomes a batch class.

start,execute and finish methods.


Start method is used to collect the records or objects to be passed to the interface method execute for processing.This method is called once at the beginning of a Batch Apex job and returns either a Database.QueryLocator object or an Iterable that contains the records or objects passed to the job.


Execute method performs the actual processing for each chunk or “batch” of data passed to the method

  • Default batch size is 200 records

This method takes the following:

  • A reference to the Database.BatchableContext object.

  • A list of sObjects, such as List<sObject>, or a list of parameterized types. If you are using a Database.QueryLocator, use the returned list.

Finish method used to execute post-processing operations (for example, sending an email) and is called once after all batches are processed.


Skeleton of a Batch Apex

public class MyBatchClass implements Database.Batchable<sObject> {
 public (Database.QueryLocator | Iterable<sObject>) start(Database.BatchableContext bc) {
 // collect the batches of records or objects to be passed to execute
 }
 public void execute(Database.BatchableContext bc, List<P> records){
 // process each batch of records
 }
 public void finish(Database.BatchableContext bc){
 // execute any post-processing operations
 }
}

Invoking a Batch Class

MyBatchClass myBatchObject =newMyBatchClass();
Id batchId =Database.executeBatch(myBatchObject); 

(OR )

you can also pass the second parameter a number as shown below to specify the number of records per batch or chunk.

  • Id batchId =Database.executeBatch(myBatchObject,100);

Sample Batch Apex Code

Batch Apex is typically stateless so we don't have track of success and failure records that are processed per batch. If you specify Database.Stateful in the class definition, you can maintain state across all transactions.


Sample Batch Apex Code Or State in Batch Apex

public class UpdateContactAddresses implements
 Database.Batchable<sObject>, Database.Stateful {
 // instance member to retain state across transactions
 public Integer recordsProcessed = 0;
 public Database.QueryLocator start(Database.BatchableContext bc) {
 return Database.getQueryLocator(
 'SELECT ID, BillingStreet, BillingCity, BillingState, ' +
 'BillingPostalCode, (SELECT ID, MailingStreet, MailingCity, ' +
 'MailingState, MailingPostalCode FROM Contacts) FROM Account ' +
 'Where BillingCountry = \'USA\''
 );
 }
 public void execute(Database.BatchableContext bc, List<Account> scope){
 // process each batch of records
 List<Contact> contacts = new List<Contact>();
 for (Account account : scope) {
 for (Contact contact : account.contacts) {
 contact.MailingStreet = account.BillingStreet;
 contact.MailingCity = account.BillingCity;
 contact.MailingState = account.BillingState;
 contact.MailingPostalCode = account.BillingPostalCode;
 // add contact to list to be updated
 contacts.add(contact);
 // increment the instance member counter
 recordsProcessed = recordsProcessed + 1;
 }
 }
 update contacts;
 }
 public void finish(Database.BatchableContext bc){
 System.debug(recordsProcessed + ' records processed. Shazam!');
 AsyncApexJob job = [SELECT Id, Status, NumberOfErrors,
 JobItemsProcessed,
 TotalJobItems, CreatedBy.Email
 FROM AsyncApexJob
 WHERE Id = :bc.getJobId()];
 // call some utility to send email
 EmailUtils.sendMessage(job, recordsProcessed);
 }
}

Best Practices

  • Minimize Web service callout times

  • Tune queries used in your batch Apex code

  • Only use Batch Apex if you have more than one batch of records. If you don't have enough records to run more than one batch, you are probably better off using Queueable Apex.

  • Use extreme care if you are planning to invoke a batch job from a trigger. You must be able to guarantee that the trigger won’t add more batch jobs than the limit.



2 views0 comments

Recent Posts

See All

Salesforce Configuration Topics

CRM - Customer Relationship Management 1.             What is CRM(Customer Relationship Management)? 2.             CRM Basic entities 3.             Sub Modules of CRM 4.             Existing CRMs Sa

Daily Information | Daliylinx are related to General information, Technology, Salesforce, Newspapers, Telugu Newspapers, Pets, Cars etc

  • Facebook