Salesforce Asynchronous Apex using Batch Apex

Batch Apex is used to run large jobs (think thousands or millions of records!) that would exceed normal processing limits. Using Batch Apex, you can process records asynchronously in batches (hence the name, “Batch Apex”) to stay within platform limits. If you have a lot of records to process, for example, data cleansing or archiving, Batch Apex is probably your best solution.

Here’s how Batch Apex works under the hood. Let’s say you want to process 1 million records using Batch Apex. The execution logic of the batch class is called once for each batch of records you are processing.

Each time you invoke a batch class, the job is placed on the Apex job queue and is executed as a discrete transaction.

This functionality has two awesome advantages:

  • Every transaction starts with a new set of governor limits, making it easier to ensure that your code stays within the governor execution limits.
  • If one batch fails to process successfully, all other successful batch transactions aren’t rolled back.

Syntax for Batch apex:

global class MyBatchClass implements Database.Batchable {

    global (Database.QueryLocator | Iterable) start(Database.BatchableContext bc) {

        // collect the batches of records or objects to be passed to execute

    }

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

        // process each batch of records

   }

   global void finish(Database.BatchableContext bc){

// execute any post-processing operations

    }

}

Syntax for Invoke a Batch apex class:

MyBatchClass myBatchObject = new MyBatchClass();

Id batchId = Database.executeBatch(myBatchObject);

Sample Batch apex code:

global class UpdateContactAddresses implements

    Database.Batchable, Database.Stateful {

  // instance member to retain state across transactions

    global Integer recordsProcessed = 0;

    global 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\”

       );

    }

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

       // process each batch of records

List contacts = new List();

  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;

    }

    global 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);

    }

}

Things to remember:

Up to 5 batch jobs can be queued or active concurrently.

The maximum number of batch Apex method executions per 24-hour period is 250,000, or the number of user licenses in your org multiplied by 200—whichever is greater.

A maximum of 50 million records can be returned in the QueryLocator object. If more than 50 million records are returned, the batch job is immediately terminated and marked as Failed.

If the startmethod of the batch class returns a QueryLocator, the optional scope parameter of executeBatch can have a maximum value of 2,000.

If the start method of the batch class returns an iterable, the scope parameter value has no upper limit.

The start, execute, and finish methods can implement up to 100 callouts each. Implement AllowsCallouts for enabling callouts from the Batch apex.

Methods declared as future can’t be called from a batch Apex class.

All methods in the class must be defined as global or public.

Leave a Comment

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