Salesforce Asynchronous Apex: How to work with Batch Apex Class

Looking for Salesforce Training & HandsOn Projects?


Batch Apex is a type of Apex code that is used to process large batches of data asynchronously. This means that the code is executed in the background, so it does not block the user interface or other concurrent requests. 


Batch Apex is a powerful tool that can be used for a variety of tasks, such as:

  • Data migration
  • Data cleansing
  • Bulk updates
  • Archiving
  • Scheduled jobs

To use Batch Apex, you must implement the Database.Batchable interface. This interface defines three methods:

  • start(): This method is called once, at the beginning of the batch job. It is used to initialize the batch job and retrieve the data that will be processed.
  • execute(): This method is called for each batch of data. It is where the actual processing of the data is done.
  • finish(): This method is called once, at the end of the batch job. It is used to clean up any resources that were used by the batch job.

Batch Apex jobs are executed in batches of 200 records. This helps to prevent the governor limits from being exceeded. Batch Apex jobs can also be scheduled to run at specific times.

Here are some of the benefits of using Batch Apex:

  • It can process large batches of data without blocking the user interface.
  • It can be used to run long-running processes.
  • It can be scheduled to run at specific times.


Here are some of the limitations of using Batch Apex:

  • It can be more complex to develop than regular Apex code.
  • It can be more difficult to debug.
  • It can be more difficult to troubleshoot problems.

In this article, we will see how to write batch classes over a set of Salesforce Records.

We will make use of the Standard Object “Case” to execute this POC.

Step-1: Let’s consider a set of open Cases with Status = ‘New’ that we need to process and set the new Status = ‘Working’. In this demo, I have a small dataset to work with but it still holds good for a large dataset as well (a really large one, remember millions of records)



Now in order to write the code, we can use any code editor of your choice (VS Code for me), but here I am making use of Salesforce Developer Console as a starting point for the sake of simplicity.

Step-2: Click on the configuration/settings wheel on the top right and select “Developer Console” options as shown below-



Step-3: With-in Developer Console click on “File > New > Apex Class” menu option to create a new Apex Class definition as shown below-



Step-4: Enter the name of your brand new Apex Class. In this demo let’s call it “MyBatchApex”



Step-5: Here I am making use of “Workbench” to test any or all of the SOQL Queries before using them in Apex Code. Note it is a best practice that every developer should follow to reduce development time errors in Apex code

Step-6: Enter the SOQL statement that you would like to use in Batch Apex “Database.getQueryLocator” function. In this demo, we will be testing SOQL getting records from Case Object

Step-7: We can see the results returned by the query. So practically these will be the records that Batch Apex Job will query and process



Step-8: To implement Batch Apex we need to implement “Database.Batchable” Interface

Step-9: We will implement the first method “start” from Interface “Database.Batchable”. This method makes use of “Database.BatchableContext” object as an input parameter. 

This parameter returns contextual information about the Batch Apex Job which might be really helpful in certain cases. 

The “start” method executes only once in the Job Lifecycle to fetch the records as per SOQL Query.

Step-10: The “start” method returns a dataset to be processed by the Batch Apex Job. 

This dataset is returned as “Database.getQueryLocator” instance which passes a set of records as per the Batch-Size (default=200 but can be configured to any reasonably optimized value). 

Hope you can notice it is the same SOQL statement that we have tested already using “Workbench”.

Step-11: The next method to discuss is the “execute” method that receives the batch of records from “start”. The “execute” method contains all the processing logic that will execute once per batch of records.

Step-12: We can read the records from the batch and process them as required.

Step-13: In this demo, we would set the Case Status from “New” to “Working”

Step-14: And then finally update the batch of records apply “Bulk Update Pattern”. So this is again a best practice to follow Salesforce recommended design patterns under different use cases. 

The developer is expected to be vigilant for such practices as the first line of defense towards rotten code blocks

Step-15: Finally we need to implement the “finish” method in order to complete the implementation of the Batch Apex Job. 

This method will be executed only once in the Job Life Cycle and it is a good place to run cleanup tasks or send notifications out or make updates to relevant objects or could something related to the job monitoring or maintenance. 

In this demo, I am just writing a simple debug statement to notify me when the Job got finished executing all batches.



Step-16: Now we need to test this implementation and the easiest way to go with it is “Anonymous Window” in Developer Console. Go to “Debug > Open Execute Anonymous Window” menu options to launch the window



Step-17: Now to test the batch class we can execute it by using “Database.executeBatch” function which takes an instance of a batchable class as input and batch size as a second input. 

In this case, we are passing the “batch_size = 2”. Execute this code & check for the debug logs. Remember we have added a debug statement in the “finish” function



Step-18: If we inspect the debug logs then we can have the message printed on completion of the job as we expect



Step-19: Now we can confirm the changes made to the Case Records by navigating to Salesforce Org. 

Notice the Status column, you find all the Cases are not in “Working” status instead of “New”



Step-20: We can also validate the results by executing SOQL Query using Workbench as earlier

Step-21: But this time we don’t see any records return matching the where clause [Status=’New’] of SOQL Statement



Step-22: Similarly we can check for records that were impacted by the batch job and got Status=’Working’

Step-23: Results are obvious as per the SOQL Query



And that is it. We have just created a brand new Batch Apex implementation.

Hope you enjoyed this article. Please leave your comments to let me know how you like the content and how you find it helpful to learn the topic.

Comments