Batch Apex in Salesforce

All You Need to Know about Batch Apex in Salesforce

Contents:

What is Batch Apex?

Batch Apex is a very powerful asynchronous process introduced by Salesforce. Which is used to process a large number of records. Because the code runs asynchronously, things are handled within the framework. When an Apex batch job is called, the records are batched using the provided execution logic. Each batch counts as a separate Apex transaction. 

Why Use Batch Apex?

  • Apex batching is used to run large jobs (eg thousands or millions of records) that exceed normal processing limits. 
  • If you have a lot of records to process, such as data cleaning or archiving, Batch Apex might be your best bet. 
  • The Batch class allows you to define a single job that can be broken down into manageable chunks to be processed individually. 

dont miss out iconDon't forget to check out: Invoke Apex Actions from Flow | Salesforce Flow Guide

Advantages of Batch Apex

  • Each transaction starts with a newly set governor limit, so it's easier to ensure that your code stays within the governor limit. 
  • If one batch is not processed successfully, all other successful batch transactions are not rolled back. 
  • You can use the Batch Apex classes to process large sets of records together on a regular basis. 

Disadvantages of Batch Apex

  • Because it runs asynchronously, troubleshooting can be difficult without coded debugging, logging, and persistent stateful reporting. It also means that it is waiting to be executed, which may delay execution. 
  • There is a limit of 5 batches that can be played at any time, so it is difficult to run the batch without checking the limit. 
  • There is still a (somewhat large) limit on the total heap size for a full batch run. This means that some very complex logic can overflow and have to be split into separate batches. 

Syntax of Batch Apex 

Invoking a Batch Class

  • LeadProcessor batchInstance = new LeadProcessor (); 

           Id batchId = Database.executeBatch(batchInstance); 

  • Id batchId = Database.executeBatch(myBatchObject, 100); 
  • AsyncApexJob job = [SELECT Id, Status, NumberOfErrors FROM AsyncApexJob WHERE ID = :batchId ]; 

Create an Apex Class with an Example:

dont miss out iconCheck out an amazing Salesforce video tutorial here: Crash Course on Apex Triggers Salesforce | Complete Guide with Real Time Scenarios

How to Execute Batch Class?

 

  • After completing your code, you need to go to Developer Console and click on Debug and Open Execute Anonymous Window. 
  • Now enter the following syntax in the box and click on Execute as given below 
  • LeadProcessor newInstance = new LeadProcessor (); 

           database.executeBatch(newInstance); 

Responses

Popular Salesforce Blogs