Batch classes in Salesforce are used to run large jobs (think thousands or millions of records!) that exceed typical processing limits. Batch Apex allows you to batch process records asynchronously while staying within the boundaries of the platform (hence the name “Batch Apex”). When you need to process many records. B. For data cleaning or archiving, Batch Apex is probably the best solution.
This is how Batch Apex works under the hood. Let’s say you process 1 million records with Batch Apex. Batch class execution logic is called once for each batch of records to be processed. Every time he calls the batch class, the job is placed in his Apex job queue and executed as a standalone transaction.
Advantage of Using Batch Apex
- Each transaction starts with a new set of governor limits, making it easier for your code to stay within governor execution limits.
- If a batch cannot be processed successfully, all other successful batch transactions are not rolled back.
Batch Apex Syntax
To write a Batch Apex class, your class must implement the Database.Batchable interface and include the following three methods:
start
The Start method is called automatically when the Apex job starts. This method collects records or objects on which to perform an operation. These records are split into subtasks and passed to the execute method.
Used to collect records or objects passed to the execute interface method for processing. This method is called once at the start of a batch Apex job and returns either a Database.QueryLocator object or an Iterable containing the records or objects passed to the job.
In most cases, a QueryLocator with a simple SOQL query is sufficient to generate a range of objects in a batch job. But if you need to do something crazy, for example, to iterate over the results of an API call or preprocess the records before passing them to the execute method, you can use a custom iterator in the “Resources” section Please check the link.
A QueryLocator object bypasses the limit on the total number of records retrieved by a SOQL query and can query up to 50 million records. However, iterables impose governor limits on the total number of records retrieved by a SOQL query.
Don’t forget to check out: Schedule Batch Apex | Asynchronous Apex in Salesforce | Learn Salesforce Development
execute
The Execute method performs the operations you want to perform on the records retrieved by the launch method.
Performs the actual processing on each block or “batch” of data passed to the method. The default batch size is 200 records. Batches of records are not guaranteed to be executed in the order received by the launch method.
This method takes the following:
- A reference to the Database.BatchableContext object.
- A list of sObjects, such as List<sObject>, or a list of parameterized types. If you are using a Database.QueryLocator, use the returned list.
finish
The Finish method runs after all batches have been processed. Use this method to send confirmation email notifications.
Used to perform post-processing operations (such as sending an email) and is called once after all batches have been processed.
Here’s what the skeleton of a Batch Apex class looks like:
Key Points About Batch Apex
- To use batch apex, create an apex class that implements the Database.Batchable interface and make the class global.
- Implement the following 3 methods:
- The default Size of batch is 200
Monitoring Batch Apex
To monitor or stop batch Apex job execution, from Setup, enter Apex Jobs in the Quick Find box, then select Apex Jobs.
Invoking a Batch Class
To invoke a batch class, simply instantiate it and then call Database.executeBatch with the instance:
MyBatchClass myBatchObject = new MyBatchClass();
Id batchId = Database.executeBatch(myBatchObject);
Optionally, you can pass a second range parameter to specify the number of records to pass to the execute method for each batch. Pro-tip: If you run into governor limits, it’s a good idea to limit this stack size.
Id batchId = Database.executeBatch(myBatchObject, 100);
An AsyncApexJob record is created for each bulk Apex call so you can track the progress of the job. View progress in SOQL and manage jobs in the Apex job queue. We’ll talk about job queues later:
AsyncApexJob job = [SELECT Id, Status, JobItemsProcessed, TotalJobItems, NumberOfErrors FROM AsyncApexJob WHERE ID = :batchId ];
Check out another amazing blog by Mohit here: Component Event Propagation in Salesforce – A Short Guide
Scheduling Batch Apex
You can also use the Schedulable interface in your batch Apex classes. The following example implements his Schedulable interface for a batch Apex class named batchable:
global class scheduledBatchable implements Schedulable { global void execute(SchedulableContext sc) { BatchApexExample b = new BatchApexExample(); Database.executeBatch(b); } }
Best Practices for Batch Apex
As with future methods, there are a few things to keep in mind when using Batch Apex. To make your batch jobs run faster, minimize web service callout times and optimize the queries used in your batch Apex code. The longer a batch job runs, the more likely it is that other jobs in the queue will be delayed if there are many jobs in the queue. Best practices include:
- Use Apex batching only when there are multiple batches of records. If you don’t have enough records to run multiple batches, we recommend using Queueable Apex.
- Optimize each SOQL query to collect records for fastest execution.
- Minimize the number of asynchronous requests made to minimize potential delays.
- Be very careful when calling batch jobs from triggers. You should be able to guarantee that your trigger will not add more batch jobs than your limit.