Friday 7 August 2020

Episode 7-Batch Apex Example in Salesforce




In this blog, we will understand why and how to write a batch apex by taking an example. Without wasting any time lets get started 😊.


WHY Use Batch Apex?

Let's say you have 1 million records to process if you use normal SOQL query in your apex code, it will run out of the governor's limits and your code will throw an exception that cannot be handled.
Here the Batch Apex which rescues and solves your problem.

Batch Apex is an apex class that implements Database. Batchable  Interface and have three methods
Start(),Execute() and finish(). We will see this methods in detail in our example.

Why Batch Apex does not exceed the Governor limit?

The Batch apex runs asynchronously to process the records in chunks i.e in batches. The default batch size is 200 records. The execute method of your class is called every time once for each batch of records and is executed as the discrete transaction. (means transactions are independent of one another).

  • Every transaction ( here transaction refers to a batch of records)  starts with the new set of governor limits, hence your code stays within the governor limits.
  • Each transaction is discrete hence if one batch fails to process successfully then all other batches that are executed successfully will not be rolled back.
I hope you have understood the advantages of using batch apex.


HOW to Use Batch Apex?


The basic template of batch apex looks like :

The Key Point to remember here is all the methods defined in the class should be public or global.

global class BtachClassSkeleton implements Database.Batchable<sObject> {

    global (Database.QueryLocator | Iterable<sObject>) start(Database.BatchableContext bc) {
        // collect the batches of records  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
    }    
}

Use Case Scenario:

We need to look at all the leads and update the description of the lead Records to 'This is the Qualified lead who is highly interested in the product' when the rating field value is 'Hot' i.e when you have the  Hot Lead in your org.


global class HotLeads implements Database.Batchable<sObject>{

    // Start method: collects all the lead records meeting the specified criteria

    global Database.QueryLocator start(Database.BatchableContext bc){
        String query='select Id,Rating from Lead where Rating=\'Hot\'';
        return Database.getQueryLocator(query);     
    }

    //Execute method: Taking a list of lead records returned  by start method  as a parameter
    // and Updating the lead description

    global  void execute(Database.BatchableContext bc,List<Lead> leadRecords){
        for(Lead l: leadRecords){
            l.Description='This is the Qualified lead who is highly interested in the product';                   
        }
        update leadRecords;
    }

    //Finish Method 

    global void finish(Database.BatchableContext bc){
        System.debug('Your records processed Successfully');
        AsyncApexJob job= [select id,Status,JobItemsProcessed,TotalJobItems,NumberofErrors
                           from AsyncApexJob where id = :bc.getJobId()];

        // sends a notification email to the job submitter that includes the job info and number of leads updated.    
    }
}

NOTE:

AsynchApex Job  Record allows you to track the progress of the batch job. For Example, you can find the information about the status of the job, Total Number of Job Items, and how many of them get processed and how many of them are error out and much more. You can view the progress by a SOQL query as used below or you can manage the job in the Apex Job Queue.


AsyncApexJob job = [SELECT Id, Status, JobItemsProcessed,
TotalJobItems, NumberOfErrors FROM AsyncApexJob WHERE ID = :batchId ];

Invoking Batch Apex:


To invoke the batch apex instantiate your class and then call Database.executeBatch with the instance.

For Example:

In order to call the above batch class, use below code:

HotLeads  batchObject = new HotLeads();
Id batchId = Database.executeBatch(batchObject, 100);

You may be wondering why the value 100 is also passed with the instance. This is an optional parameter that allows you to pass the value for no of records that should be passed into the execute method for each batch. What if you do not pass any value?  .Then, in that case, it will take a default value as 200.

                                                                                                                                                                       

Best Practices:

  • Ensure using batch apex when you have more batch of records, otherwise, it is always recommended to use queueable apex instead.
  • For Fast Execution of your batch apex, the SOQL Queries should be tuned and also minimize the web service callout time.
  • Minimize the use of asynchronous requests to minimize the delay.
  • If your batch apex is invoked by the trigger then extreme care has to be taken in terms of limit of batches executed by the trigger.
Please check out  the below link of my earlier blog on Asynchronous Apex :


Thanks for reading my blog, hope you have learned about batch apex and how to implement them.
Please stay tuned to know about the scheduling of batch apex and what is the use of the           
 Database. stateful interface with the use case example.
Till then keep learning and keep sharing your knowledge.✌



































No comments:

Post a Comment

If you have any doubts ,Please let me know.

Episode 13 : RollUp Summary Trigger for Lookup Relationship

 As we all know we can use roll-up summary field logic only for the master-detail relationship, but in case you have the business requiremen...