top of page

Batch Apex for processing huge number of records

Updated: Jun 4, 2020

It breaks down a huge batch into manageable chunks.

Real life use - a data cleansing operation that goes through all Accounts and Opportunities on a nightly basis and updates them if necessary, based on custom criteria.

It is called repeatedly to process very large amounts of data.


Use case - To rate all accounts daily based on the value of opportunities closed in the last year. The account with the highest value of opportunities closed in the last year should be rated number 1 and so on until the account with the lowest value of closed opportunities.



You can only have five queued or active batch jobs at one time.


Steps to create a Batch Apex:

  1. write an Apex class that implements the Salesforce-provided interface Database.Batchable: eg: global class batchClass implements Database.batchable

  2. The Database.Batchable interface contains three methods that must be implemented. start method: Used to collect the records or objects to be passed to the interface method execute for processing. You can use a QueryLocator with a simple SOQL query to generate the scope of objects in the batch job. execute method: Performs the actual processing for each “batch” of data passed to the method. The default batch size is 200 records that forms the second parameter of this method. finish method: Used to execute post-processing operations (for example, sending an email) and is called once after all batches are processed. Here’s what the skeleton of a Batch Apex class looks like: global class MyApexBatch implements Database.Batchable<sObject> { global (Database.QueryLocator | Iterable<sObject>) start(Database.BatchableContext bc) { // collect the batches of records or objects to be passed to execute } global void execute(Database.BatchableContext bc, List<P> records){ // process each batch of records } global void finish(Database.BatchableContext bc){ // execute any post-processing operations } }

  3. To invoke a batch class, simply instantiate it and then call Database.executeBatch with the instance: MyApexBatch myBatchObject = new MyApexBatch(); Id batchId = Database.executeBatch(myBatchObject);

  4. To schedule the batch - https://help.salesforce.com/articleView?id=code_schedule_batch_apex.htm&type=5

Refer to the following for implementation - https://github.com/JohnsonTitus/apxApexBatch.git/apxApexBatch/tree/master/force-app/main/default/classes To learn more - https://trailhead.salesforce.com/en/content/learn/modules/asynchronous_apex/async_apex_batch



Recent Posts

See All

Comments


Post: Blog2_Post

©2020 by SalesforceDemystified. Proudly created with Wix.com

bottom of page