Salesforce Batch Apex

By in
659
Salesforce Batch Apex

When we need to process thousands of records in the background upon whom we won’t be able to perform DMLs in the sync transaction given their volume. To help with this problem, we can use Batch Apex in Salesforce.

 

Syntax

public class RecordsProcessingBatch implements Database.Batchable<sObject>{

 

public Database.QueryLocator start(Database.BatchableContext BC){

return Database.getQueryLocator(‘Select Id From Contact Where isActive = false ’);

}

 

public void execute(Database.BatchableContext BC, List<Contact> contacts){

//Process contacts

}

 

public void finish(Database.BatchableContext BC){

//Send email, etc

}

}

 

Batch Apex in Salesforce

Understanding the Code

To use the batchable interface, you’ll need to compulsorily implement 3 methods that make the batch run in chunks. Those methods are,

  1. start
  2. execute
  3. finish

 

  1. start

We query the records that are supposed to be processed. A batch can query up to 50 million records per transaction.

  1. execute

For every chunk, the records from the start method are passed to the execute method. Suppose the chunk size mentioned is 50 and the total number of records in the org is 200 then execute method will be called 4 times. Each time with 50 records.

  1. finish

When the process is done with processing records like performing updates to a contact record,  this method can be used to send out emails to all the records that’ve been processed.

 

Initiating a Batch

A batch class can be initiated by using Database.executeBatch(BatchInstance, numberOfRecords);

Maintaining State of Variables in Batch Apex

Every transaction of Batch Apex is a discreet one. That means no two transactions will have the same value of the instance variables.

Static member variables don’t retain their values and are reset for every new transaction. Maintaining state is very useful when you need to count or summarise records as they’re processed. For this, you can use Database.Stateful interface.

 

Conclusion

As mentioned in the article, you can always use a Batch class when the processing required is too high. As large volumes of data can’t be processed in a sync transaction.

 

To learn more about Apex in Salesforce, check out some of my related articles below!

 

Additional Resources

Cover Photo by Diane Helentjaris on Unsplash

Leave a reply

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