What is Batch Apex in Salesforce?

In this section, you will understand about Batch Apex in Salesforce in detail. Consider a situation wherein you have to process large amounts of data on a daily basis and have to delete some unused data. It would be difficult to manually do so. This is where batching with Apex Salesforce comes to your rescue.

Watch this informative video on Salesforce from Intellipaat:

Batch Apex in Salesforce

Youtube subscribe

Before going deep into the concept of Batch Apex, let’s see the topics covered in this section:

Batch Apex in Salesforce is specially designed for a large number of records, i.e., here, data would be divided into small batches of records, and then it would be evaluated. In other words, Batch class in Salesforce is specifically designed to process bulk data or records together and have a greater governor limit than the synchronous code.

Advantages of Batch Apex in Salesforce

  • Whenever a transaction is executed, Batch Apex ensures that the code stays within the governor limit.
  • Until a batch is not successfully executed, Batch Apex won’t execute the following batches.
  • A large set of records can be processed together on a regular basis using Batch Apex classes.
  • The interface can be scheduled to run batches at different time periods.
  • Asynchronous operations can be implemented by Batch Apex classes.
  • Batch jobs are invoked programmatically during the runtime and can be operated on any size of records, with a maximum of 200 records per batch. You can break down a larger record data into 200 records per batch to execute it better.

Learn more about Salesforce from this Salesforce Training in New York to get ahead in your career!

Why use Batch Apex in Salesforce instead of the normal Apex?

There are various reasons why Batch Apex is better than normal Apex.

  • SOQL queries: Normal Apex uses 100 records per cycle to execute SOQL queries. Whereas, Batch Apex does the same in 200 records per cycle.
  • Retrieval of SOQL queries: Normal Apex can retrieve 50,000 SOQL queries but, in Batch Apex, 50,000,000 SOQL queries can be retrieved.
  • Heap size: Normal Apex has a heap size of 6 MB; whereas, Batch Apex has a heap size of 12 MB.
  • Errors: When executing bulk records, Normal Apex classes are more vulnerable to encountering errors as compared to Batch Apex.

Get familiar with the top Salesforce Interview Questions to get a head start in your career!

Batch Class in Salesforce

When using a Batch class in Salesforce, the batchable interface needs to be implemented first. It has the following three methods:

  • Start: This method is called at the starting of a batch job to collect the data on which the batch job will be operating. It breaks the data or record into batches. In some cases, the ‘QueryLocator’ method is used to operate with the simple SOQL query to generate the scope of objects inside a batch job.
    • Syntax:
global void execute(Database.BatchableContext BC, list<sobject<) {}
  • Execute: This method executes after the Start method, and it does the actual processing for each batch, separately.
    • Syntax:
global void execute(Database.BatchableContext BC, list<sobject<) {}
  • Finish: This method will be called at last. Since this method is called in the end, it is responsible to perform post-processing operations such as sending an email. When this process is called all batches are already executed.
    • Syntax:
global void finish(Database.BatchableContext BC) {}

Creating an Apex Batch Class in Salesforce with an Example

Batch Apex splits the records into batches and processes them asynchronously, which helps the records to be processed in multiple threads. Without exceeding the processing limit, batch Apex can run through millions of records. Also, if one batch is failed to process successfully, the successful transactions will not be rolled back. 

Before writing Batch apex class, you have to implement the Database.Batchable interface. If you don’t know what an interface is, it’s similar to a class where none of its functions are implemented. However, the signature of each function is there with an empty body. This interface has three main methods that must be implemented: start(), execute(), finish(). 

Now, let’s go through the steps given below and create a Batch class in Salesforce:

Step 1: Search for Apex Salesforce Classes in Setup

Creating a Batch Apex with an Example Step 1

Step 2: Once you open Salesforce Apex Classes, click on New to create a new Apex Class

Step 2

Step 3: Below is the screen on which you’ll have to write your code

Step 3

The following is the program that updates the account name in the account object with the keyword ‘Updated’ after the account name.

Step 3 A

// Batch Job for Processing the Records

  global class batchAccountUpdate implements Database.Batchable<sObject> {

// 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<Account> scope) {

         for(Account a : scope)

         {a.Name = a.Name + 'Updated';            

         }

         update scope;

    }   

    // Finish Method

    global void finish(Database.BatchableContext BC) {

    }

}

Learn new Technologies

How to Execute Batch Class in Salesforce

Executing a Batch class in Salesforces only takes a few clicks on the Developer Console. So, follow the steps given below to execute the batch class you created earlier. We’ve considered the above batch class as an example. If you want to execute another file, you can change the name accordingly.

 

Step 4: After writing the code, you’ll have to go to Developer Console and click on Debug and then on Open Execute Anonymous Window. You’ll see the following screen:

Step 4

The basic syntax of the execution code will be: 
Id <variable_name> = new <variable_name>;
database.ExecuteBatch(new <class_name>(), batch_size);

Enter the following code in the box and click on Execute

batchAccountUpdate b = new batchAccountUpdate();
database.executeBatch(b);

step 5

The following will be the output after you click on Execute

click on Execute

As you can see, the status Success means that the account details have been updated.

To learn in-depth about Workflow in Salesforce, sign up for an industry based Salesforce Training.

Batch Class Schedule in Salesforce

You can schedule your batch Apex class using the developer console or scheduler. These batch classes can then be executed at a particular time. However, you need to write the Apex class able to execute the schedulable interface. You can also chain the two or more apex batch classes together to execute one job after another. Moreover, you can split an Apex record into batches and schedule the groups of them to execute at a particular time. 

Below is an example of a Schedulable Apex class interface:


Global class apexScheduler implements Schedulable
{
Global void execute(SchedulableContext sc)
{
batchAccountUnpdate b=new batchAccountUpdate();
}
}

Save the above Apex class on your device. Now, go to the Setup>> Apex Classes>> ScheduleApex, browse the ScedulerApex class, and set the execution time

Come to Intellipaat’s Salesforce Community if you have more queries on Salesforce!

I hope, you had fun learning Batch Apex! In this section, you learned about Salesforce Apex Classes and Batch Apex in Salesforce and you implemented it as well. In the next section of this Salesforce tutorial, you will be learning about Workflow Rules in Salesforce.

Course Schedule

Name Date
Salesforce Certification 2021-08-07 2021-08-01
(Sat-Sun) Weekend batch
View Details
Salesforce Certification 2021-08-14 2021-08-08
(Sat-Sun) Weekend batch
View Details
Salesforce Certification 2021-08-21 2021-08-15
(Sat-Sun) Weekend batch
View Details

Leave a Reply

Your email address will not be published. Required fields are marked *