Batch Apex is an asynchronous execution of the Salesforce Apex class, purely designed for processing a large number of records and has more flexibility in governor limits than the synchronous code. As per the name, the batch word is used when you want to process a bulk amount of data efficiently without any error that you need to apply some logic certainly.
The logic of the batch class is executed once for each batch of records you are processing and flexibility is you need to decide number of records you want to process in single batch. Each time you run a batch class, the job is placed on the Apex job queue and is executed as a individual transaction.
Advantages of Salesforce Apex Batch Class ?
1) Every transaction starts with a new set of governor limits, making it easier to ensure that your code stays within the governor execution limits.
2) If one batch fails to process, all other successful batch transactions aren’t rolled back.
3) Batch classes give users the ability to automate repetitive tasks and processes, eliminating manual work and errors associated with them.
How to create a new Batch Apex Class in Salesforce ?
The Salesforce Batch Apex governor limits are the limits that Salesforce applies to certain operations when running batch Apex jobs. The limits are designed to provide a secure, reliable, and scalable environment for all Salesforce customers. The limits are comprised of the following:
1. Login to Salesforce and click on Setup.
2. Navigate to Apex Classes and click "New".
3. Give the class a name.
4. Accept the default class type of "Apex Class".
5. Enter your Apex class code.
6. Click "Save".
To write a batch APEX class, you should first implement the “Database.Batchable” interface in the Salesforce and including the execution of these three methods.
- Start
- Execute
- Finish
Below is the sample code for batch class
global class WMG_Batch_Class implements Database.Batchable { global Database.QueryLocator start(Database.BatchableContext BC){ //Query Here } global void execute(Database.BatchableContext BC, List scope){ //Generate templates } global void finish(Database.BatchableContext BC){ //Send an email } }
Start: This method is used to collect records that need to be passed to an execute method for processing. This method is called at the beginning when Batch apex starts to execute. In most of the cases, the “QueryLocator” method is used to write the simple SOQL query and to generate the scope of objects within a batch job.
Execute: This method will perform the actual processing for each batch where data needs to be passed with the help of a method. The default size defined for each batch is 200 records maximum, and we can set it custom according to our need. If the processing is more you should keep batch size low so that processing can be completed for each records.
Finish: This method will perform post-processing operation like email sending or more once all batches are executed successfully.
Salesforce Apex Batch class Example - Append 'Test' to LastName for all Accounts
global class batchAccountNameUpdate implements Database.Batchable<sObject> { global Database.QueryLocator start(Database.BatchableContext BC) { String query = 'SELECT Id,Name,FirstName,LastName FROM Account'; return Database.getQueryLocator(query); } global void execute(Database.BatchableContext BC, List<Account> scope) { for(Account a : scope) { a.LastName = a.LastName + ' Test'; } update scope; } global void finish(Database.BatchableContext BC) { System.debug('Execution Completed') } }
How to manually execute Apex Batch Class ?
1. Login to Salesforce and click on Setup.
2. Select Developer console
3. Now Developer console will open in new window
4. Select Debug from menu bar
5. Select 'Open Execute Anonymous Window'
6. Add below code to Popup opened
batchAccountNameUpdate obj=new batchAccountNameUpdate();
Database.executeBatch(obj,10);
7. Click on Execute
Here in Database.executeBatch(obj,10); 10 is batch size. Default batch size is 200
How to create a Test Class for Apex Batch ?
1. Login to Salesforce and click on Setup.
2. Navigate to Apex Classes and click "New".
3. Give the class a name. (Append Test at end of name)
4. Accept the default class type of "Apex Class".
5. Enter your Apex class code.
6. Click "Save".
Salesforce Test class example for - Append 'Test' to LastName for all Accounts
@isTest public class batchAccountNameUpdateTest { testMethod private static void testMethod(){ List<Account> accountList = new List<Account>(); Account myAccount = new Contact(FirstName = 'First', LastName = 'Account', Email = 'firstaccounttest@gmail.com', MobilePhone = '650-886-8899'); insert myAccount; accountList.add(myAccount); batchAccountNameUpdate batchObj1 = new batchAccountNameUpdate(); Test.startTest(); Database.executeBatch(batchObj1, 10); Test.stopTest(); System.assertEquals(1, [select count() from Account where LastName ='Account Test']); } }
Conclusion
Salesforce batch class is a class that can be used to process large numbers of records asynchronously. It uses the same Apex programming model that developers use for synchronous transactions, but operates over a larger number of records and more extended time frame. Once created, Salesforce batch classes can be scheduled, monitored, and managed programmatically. They are a great way to handle large data sets that need to be processed in a periodic or scheduled manner.
Sahil is a highly skilled and dedicated Salesforce Certified Platform Developer with a passion for creating efficient and innovative solutions within the Salesforce ecosystem. With an insatiable curiosity and a relentless drive for excellence, he has become a go-to expert in developing custom applications and functionalities on the Salesforce platform.
Comments are closed.