Batch Apex in Salesforce

Batch Apex is asynchronous execution of Apex code, specially designed for processing a large number of records and has greater flexibility in governor limits than the synchronous code.

Key points about batch Apex

  • In order to use batch apex, an apex class must implement Database.Batchable interface and the access of the class should be global (Not Compulsory but helpful when developing classes for the managed package).
  • Implement the following 3 methods
    • start()
    • execute()
    • finish()
  • The default batch size is 200

Apex Code:

global class BatchApexExample implements Database.Batchable<sObject> {
    global Database.QueryLocator start(Database.BatchableContext BC) {
        // collect the batches of records or objects to be passed to execute
         
        String query = 'SELECT Id, Name,Industry FROM Account';
        return Database.getQueryLocator(query);
    }
     
    global void execute(Database.BatchableContext BC, List<Account> accRecordList) {
        
        // process each batch of records default size is 200
        for(Account acc : accRecordList) {        
            // Update the Account Name 
            acc.Name = acc.Name + 'forceScript';
        }
        try {
            // Update the Account Record
            update accRecordList;
         
        } catch(Exception e) {
            System.debug(e);
        }
         
    }   
     
    global void finish(Database.BatchableContext BC) {
        // execute any post-processing operations like sending email or creating task

    }
}

Executing a Batch Class

We can create another apex class to call our newly created batch class or we can use Execute Anonymous Window to invoke our batch class. We can use execute to execute the whole code in the window or we can first select the code and then we can use Execute Highlighted button to execute only the selected/highlighted code.

Scheduling Batch Apex

Use the Schedulable interface with batch Apex classes to schedule a batch class. The following example implements the Schedulable interface for a batch Apex class called batchable. We can now schedule the below-mentioned apex class that will execute on specific schedule time.

Apex Code:

global class scheduledBatchable implements Schedulable {
    global void execute(SchedulableContext sc) {
      BatchClassExample batchObject = new BatchClassExample (); 
       Database.executeBatch(batchObject);
    }
 }

Test class for batch Apex

@isTest
private class BatchClassExampleTest {
    static testmethod void test() {
        // Create test accounts to be updated by batch
    Account[] accList = new List();
    for (Integer i=0;i<100;i++) {
        Account acc = new Account(Name = 'Account ' + i);
        accList.add(acc);
    }
    insert accList;
 
        Test.startTest();
            BatchClassExample batchObject = new BatchClassExample();
        Database.executeBatch(batchObject);
        Test.stopTest();
        // Verify accounts updated
    Account[] accUpdatedList = [SELECT Id, Name FROM Account];
    System.assert(accUpdatedList[0].Name.Contains('forceScript'));
    }
}

Best Practices for batch Apex

  • 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.
  • Tune any SOQL query to gather the records to execute as quickly as possible.
  • Minimize the number of asynchronous requests created to minimize the chance of delays.
  • 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.