Salesforce Batch Jobs 101: Configuring Salesforce Apex Jobs Simplified

By: Published: April 8, 2022

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.

In this article, you will learn about Salesforce Batch Jobs, Batch Apex, and how to create, configure, and execute Batch Apex classes and Salesforce Batch Jobs. 

Table of Contents

Prerequisites

A fundamental understanding of batch processing.

What is Salesforce?

Salesforce Batch Jobs: Salesforce logo
Image Source

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.

Simplify your Data Analysis with Hevo’s No-code Data Pipelines

Hevo Data, a Fully-managed Data Pipeline platform, can help you automate, simplify & enrich your data replication process in a few clicks. With Hevo’s wide variety of connectors and blazing-fast Data Pipelines, you can extract & load data from Salesforce (among 100+ sources) straight into your Data Warehouse or any Databases. To further streamline and prepare your data for analysis, you can process and enrich raw granular data using Hevo’s robust & built-in Transformation Layer without writing a single line of code!

Get Started with Hevo for Free

Hevo is the fastest, easiest, and most reliable data replication platform that will save your engineering bandwidth and time multifold. Try our 14-day full access free trial today to experience an entirely automated hassle-free Data Replication!

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. 

Salesforce Batch Jobs: Step 1a
Image Source
  • Initially, open your Salesforce workspace and search for Apex Classes in the Setup section.
Salesforce Batch Jobs: Step 1b
Image Source
  • Then, open the Salesforce Apex Classes and select the New tab to create a new Apex, as shown in the above image.
Salesforce Batch Jobs: Step 1c
Image Source
  • 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.

Salesforce Batch Jobs: Step 2a
Image Source
  • 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.
Salesforce Batch Jobs: Step 2b
Image Source
  • After entering the execution code, click on the “Execute” button.
  • You will get the output, as shown below.
Salesforce Batch Jobs: Step 2c
Image Source
  • In the output screen, you can see the status as “Success,” which means the account details are updated successfully.

What makes Hevo’s ETL Process Best-In-Class

Providing a high-quality ETL solution can be a difficult task if you have a large volume of data. Hevo’s automated, No-code platform empowers you with everything you need to have for a smooth data replication experience.

Check out what makes Hevo amazing:

  • Fully Managed: Hevo requires no management and maintenance as it is a fully automated platform.
  • Data Transformation: Hevo provides a simple interface to perfect, modify, and enrich the data you want to transfer.
  • Faster Insight Generation: Hevo offers near real-time data replication so you have access to real-time insight generation and faster decision making. 
  • Schema Management: Hevo can automatically detect the schema of the incoming data and map it to the destination schema.
  • Scalable Infrastructure: Hevo has in-built integrations for 100+ sources (with 40+ free sources) that can help you scale your data infrastructure as required.
  • Live Support: Hevo team is available round the clock to extend exceptional support to its customers through chat, email, and support calls.
Sign up here for a 14-day free trial!

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. 

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. Check out our unbeatable pricing to help you choose the right plan for your data needs.

Share your experience of learning about Salesforce Batch Jobs! Let us know in the comments section below!

Roxana Raducanu
Freelance Technical Content Writer, Hevo Data

Roxana loves solving the intricacies of data integration and analysis to data teams by offering informative content to assist individuals in understanding these complex subjects.

No-code Data Pipeline for Salesforce