Salesforce is one of the most popular customer relationship management tools that allow you to streamline Customer Interactions, Marketing Operations, and Overall Sales.
- According to a report, over 150,000 websites use Salesforce as their Customer Relationship Management tool.
- Consequently, Salesforce is also used in business scenarios that require processing a colossal amount of records or data that would exceed normal processing limits.
- In such scenarios, Salesforce’s Batch Apex comes to the rescue since it is mainly designed to process a plethora of data.
- The Batch Apex method uses an asynchronous processing method to partition data into multiple batches of records and chunks, making it easy for a developer to handle and assess enormous volumes of data.
Prerequisites
A fundamental understanding of batch processing.
How to Create and Configure Salesforce Batch Jobs?
Before creating and configuring Batch Apex, you have to write an Apex class that implements the Salesforce-provided interface called “Database.Batchable.” This interface is implemented by three methods such as Start, Execute, and Finish.
- Start: To collect the data or objects to provide to the following interface method, execute, you must call the start method at the start of a Batch Apex process. The start method either returns a Database.QueryLocator object or an iterable containing the records or objects provided to the job.
Syntax:
public (Database.QueryLocator | Iterable<sObject>) start(Database.BatchableContext bc) {}
- Execute: The execute method should be called when it is necessary to process each batch of data. This method is invoked for each batch of records passed to it. The Execute method always runs after the Start method and performs the actual processing for each batch individually. Batches of records typically execute in the order in which they are received from the start method. However, the sequence in which batches of data execute is also determined by a variety of factors.
Syntax:
public void execute(Database.BatchableContext BC, list<P>){}
- Finish: As the name implies, this method is called at the end after executing all batches. This method is also used to send confirmation emails or to execute post-processing tasks since it is invoked at the end.
Syntax:
public void finish(Database.BatchableContext BC){}
Along with the above-mentioned methods, you have to call an object called “Database.BatchableContext” while implementing batch operations in Salesforce. This object is also used to monitor the status of the batch job in Salesforce.
Step 1: Creating a Batch Apex class
Now, you are all set to create a Batch Apex class in Salesforce.
- Initially, open your Salesforce workspace and search for Apex Classes in the Setup section.
- Then, open the Salesforce Apex Classes and select the New tab to create a new Apex, as shown in the above image.
- Now, you are redirected to the coding panel, where you have to write and execute code. Execute the following code to update the account name in the account object by adding the keyword ‘Updated’ after the account name.
// Batch Job for Processing the Records
global class batchAccountUpdate implements Database.Batchable {
// Start Method
global Database.QueryLocator start(Database.BatchableContext BC){
String query = 'SELECT Id,Name FROM Account';
return Database.getQueryLocator(query);
}
// Execute method
global void execute(Database.BatchableContext BC, List scope) {
for(Account a : scope)
{a.Name = a.Name + 'Updated';
}
update scope;
}
// Finish Method
global void finish(Database.BatchableContext BC) {
}
}
Step 2: Executing a Batch class in Salesforce
After writing the code in the coding panel, you have to follow some simple steps to execute the batch class in Salesforce. It only takes a few clicks on the Developer Console to execute a Batch Class in Salesforce. To run the Batch Class you built before, follow the procedures described below. If you want to run a different file, modify the class and method name accordingly.
- For executing the batch class, navigate to the Developer Console and select Debug, and then, click on “Open Execute Anonymous Window.”
- Now, you will see the Execution screen that resembles the following image.
- In Salesforce, the basic syntax for executing a batch class is given below.
Id <variable_name> = new <variable_name>;
database.ExecuteBatch(new <class_name>(), batch_size);
- According to the syntax, you have to configure your batch class execution code, as given below.
batchAccountUpdate b = new batchAccountUpdate();
database.executeBatch(b);
- Now, enter the following code in the “Enter Apex Code” dialogue box.
- After entering the execution code, click on the “Execute” button.
- You will get the output, as shown below.
- In the output screen, you can see the status as “Success,” which means the account details are updated successfully.
Step 3: Submitting Salesforce Batch Jobs
- After creating, configuring, and executing a Batch Apex class in Salesforce, you have to submit the previously created batch as Jobs or pipelines.
- To start a batch job programmatically, you can use the Database.executeBatch method. You have to remember that, on calling Database.executeBatch, Salesforce adds the process to the queue, and the actual execution may be delayed depending on the availability of the service.
- The Database.executeBatch function takes two parameters into consideration:
- An Instance class that implements the “Database.Batchable” interface.
- An optional parameter scope that determines the number of records to pass into the execute method.
- The optional scope parameter of Database.executeBatch can have a maximum value of 2,000. If the value is increased, Salesforce divides the records into smaller batches of up to 2,000 records.
- Database.executeBatch returns the AsyncApexJob object ID, which is further used to track or monitor the job’s progress.
- Now, execute the following code to implement the batch submitting process in Salesforce.
ID batchprocessid = Database.executeBatch(reassign);
AsyncApexJob aaj = [SELECT Id, Status, JobItemsProcessed, TotalJobItems, NumberOfErrors FROM AsyncApexJob WHERE ID = batchprocessid];
Step 4: Holding Salesforce Batch Jobs in Apex Flex Queue
By creating and pushing Salesforce Batch Jobs in Apex Flex Queue, you can submit up to hundreds of jobs in a single queue. Database.executeBatch throws a LimitException and does not add any new jobs to the Apex flex queue if it has more than 100 jobs. By adding Salesforce Batch Jobs to the Apex Flex Queue, you can also monitor the statuses of the previously submitted jobs. All possible statuses that you get after submitting Salesforce Batch Jobs to the queue are listed below.
- Holding: This denotes that the job has been submitted and is being held in the Apex flex queue until system resources are available to queue it for processing.
- Queued: The batch job is waiting for execution.
- Processing: The batch job is being processed.
- Preparing: The preparing status indicates that the batch job’s start method has been called for execution. Depending on the size of the batch of records, this status can last a few minutes.
- Aborted: The batch job is aborted by the user.
- Completed: The batch job is successfully executed.
- Failed: The batch job failed and required a re-run.
Limitations of Batch Apex
- The maximum number of Batch Apex method executions per day is 250,000. This limit applies to the entire organization and is shared by all asynchronous Apex methods, including Batch Apex, Queueable Apex, Scheduled Apex, and future methods.
- If no size is supplied in the optional scope parameter of executeBatch, Salesforce divides the records returned by the start method into batches of 200.
- The QueryLocator object of the Batch Apex can only return 50 million records. If more than 50 million records are returned, the batch task is terminated and tagged as ‘failed.’
- In an organization, only one start method of a Batch Apex job can be used at the same time.
What is Salesforce?
Founded by Marc Benioff and Parker Harris in 1990, Salesforce is a Cloud-based Customer Relationship Management platform that enables you to manage and monitor Sales, Customer Activities, Lead Generation, Lead follow-ups, Marketing, and more. In other words, Salesforce offers Customer Relationship Management (CRM) services as well as a complementing set of enterprise tools for customer support, analytics, marketing automation, and business-based application development. Salesforce mainly works by storing customer contact information such as names, addresses, and phone numbers, as well as tracking customer behavior like website visits, phone calls, and emails and then leveraging that information to generate more leads for business growth.
What is Batch Apex?
In Salesforce, Batch Apex is used for processing and executing large jobs that might exceed ordinary processing restrictions. As its name implies, Batch Apex is used to asynchronously process jobs in batches, thereby achieving real-time Batch Processing. Batch Apex is the best solution if you have a large number of data to process, such as Data Cleansing or Archiving. For example, if you wish to process 1 million records with Batch Apex, the batch class execution logic is called once for each batch of records processed by Salesforce. As a result, whenever you call or invoke a batch class, the job is queued in Apex and processed as a distinct transaction.
Conclusion
In this article, you learned about Salesforce, Batch Apex, and how to create, configure, and execute Batch Apex classes in Salesforce. This article mainly focused on creating batch class Apex to execute and submit Salesforce Batch Jobs. However, you can also proceed with the process of scheduling the Salesforce Batch Jobs to execute at a specified or pre-determined time interval. In case you want to export data from Salesforce into your desired Database/destination, then Hevo Data is the right choice for you!
Hevo Data, a No-code Data Pipeline helps you transfer data from various data sources like Salesforce into a Data Warehouse of your choice for free in a fully-automated and secure manner without having to write the code repeatedly.
Visit our Website to Explore Hevo
Hevo with its strong integration with 100+ sources(Including 40+ Free Sources like Salesforce), allows you to not only export & load data but also transform & enrich your data & make it analysis-ready in a jiffy.
Want to take Hevo for a spin? Sign Up here for a 14-day free trial! and simplify your Salesforce Data Integration process with Hevo. Pick the ideal plan for your team based on your requirements.
Share your experience of learning about Salesforce Batch Jobs! Let us know in the comments section below!
Roxana is a dedicated technical content writer with over 15 years of experience specializing in technology and SaaS. She excels at transforming complex technical subjects into engaging content, covering areas from AI to software development. Deeply invested in the latest tech trends, she consistently delivers insightful and captivating material.