Today's Offer - Salesforce Certification Training - Enroll at Flat 10% Off.

- Salesforce Blogs -

A Definitive Guide to Batch Apex Class in Salesforce

To learn how to write batch classes in Salesforce, let us first understand what is batch apex class, when to use Batch Apex, and best practices for writing a batch apex class. Then we will discuss the syntax for Batch Apex class in detail so that you can learn practical concepts too.

Here, we will be covering the following topics:

  1. What is Batch Apex Class?
  2. When to use Batch Apex?
  3. Governor Limits Defined for Batch Apex
  4. How to write a Batch APEX Class?
  5. Best Practices 

What is Batch Apex Class?

As the name suggests, the batch word is used when you want to process a bulk amount of data effectively without any error that you need to apply some logic certainly. The Batch Apex class can be used conveniently here to perform a variety of tasks in the real-time like data cleaning, data archiving, data analytics to maintain the quality. In simple words, Batch Apex classes are designed specially to process voluminous data or records together and it has maximum governor limits than the synchronous code.

Why batch apex is better than normal apex classes?

Area Normal Apex Batch Apex
SOQL Queries 100 records per cycle 200 records per cycle
Records retrieval by SOQL Queries 50,000 50,000,000
Heap Size 6MB 12MB

When to use Batch Apex?

Batch Apex is an essential requirement when you wanted to execute bulk records, if you are using regular apex classes then chances of errors are higher and it may hit the governor limits too. A maximum of 200 records can be passed to every batch here. The concept has plenty of awesome advantages that you should check before moving ahead –

Read: Salesforce Service Cloud Tutorial - Facts & Features You Need to Know
  • Each transaction is executed with a set of defined governor limits, batch Apex concept makes sure that code should stay within governor limits only.
  • In case, one batch is not executed successfully then it will not roll back transactions of other batches.
  • If you wanted to process a large set of records together on regular basis then you should opt for the batch apex classes.
  • When you want an operation to be asynchronous then implement the batch apex class. The interface can be implemented by developers only. The batch jobs are invoked programmatically during runtime. It can be operated on any size of records, but you can add maximum 200 records per batch. If the size of the record set is larger then 200 then break it down into small manageable chunks.
  • Most importantly, the interface can be scheduled to run batches at different time periods.

Governor Limits Defined for Batch Apex

Before you write batch apex code, you should focus on these governor limits for effective dealing with classes.

  • There is a maximum of five active or queued batch jobs are allowed for APEX.
  • At a particular time period, one user can open up to 50 query cursors. If the user attempts to open a new one the oldest 50 cursors will be released. Keep in mind that this limit is different for start method in the Batch APEX class that could have maximum five query cursors open at a particular time.
  • Other than start method, the rest of the methods have limit up to 50 cursors. This limit is tracked differently for multiple features in Force.com. For example, for a particular method, you could have 50 batch cursors, 50 Apex query cursors, and 50 VisualForce cursors open at the same time together.
  • For a database in the batch APEX, maximum of 50 million records can be returned at a particular time. Once all 50 million records are returned, the batch job will be terminated automatically and it is marked as the “Failure” in the end.
  • The default size for a record set in batch APEX is 200. The governor limits should always be redefined for each set of records as per the requirement.
  • When we are talking about the callouts then start, execute, and the finish methods are limited to ten callouts per method execution.
  • There is a limit set for hours as well. For example, you can execute a maximum number of 250,000 batch execution in 24 hours.
  • At one time, only one start method will run for an organization. The batch jobs that are not started yet will stay in queue until they are not started. Keep in mind that this limit will not set any batch job to failure or it will not stop the execution of any batch APEX jobs but running in parallel if there are more than one jobs scheduled in the batch.

How to write a Batch APEX Class?

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.

1). Start method

This method is used to collect objects or records that need to be passed to an interface 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 play with the simple SOQL query and to generate the scope of objects within a batch job. In case, you wanted to do something crazy then call the API records before they are passed for the execution. salesforce Curriculum Further, if you wanted to set the governor limits for a total number of records retrieved by the SOQL queries then you can query up to 50 million records together. With the help of an iterable object, the governor limit for a total number of records is retrieved by SOQL queries through enforcement.

Read: Salesforce Integration with SharePoint and LinkedIn

2). Execute Method

This method will perform the actual processing for each batch or chunk where data needs to be passed with the help of a method. The default size defined for each batch is 200 records maximum. If the size of record set is larger, break it down into manageable pieces first before you execute them. If size is not defined well then records will not be executed in the same order as they were received by start method.

3). Finish method

This method is responsible to perform post-processing operation like email sending or more once all batches are executed successfully. Here is the basic syntax of a batch APEX class how are they written in the Salesforce. Batch Apex Class in Salesforce

How to use state in batch apex class?

A batch apex class is usually stateless and execution of each job in the batch is considered a discrete transaction. For example, if some batch class contains more than 1000 records then based on the default size concept total five transactions will be performed here with a record set of 200 each. Here you need to specify the Database.Stateful method in the class definition to maintain the state across all transactions. free salesforce demo With the help of this method, the member variables could always retain their values between multiple transactions. You must be thinking why it is necessary but maintaining state is beneficial to summarize records as they are processed. For example, when we are updating contact records in our batch then you wanted to keep track of the total records affected so that same can be included for the notification email list. Now you know how to write a batch class with the help of three methods and defining state for the database. Don’t forget to practice a few examples to get a better idea of the concept. Keep in mind that APEX development and testing goes hand to hand. Every time you add some records, call the batch APEX class and check if contacts are updated properly or not as per the specified requirements.

Read: Salesforce CRM vs. SAP CRM- Which One is Better?

Best Practices:

As discussed earlier, there are always certain things you should keep in mind when using the Batch Apex class. To make sure that batch jobs are executing faster, you should minimize the callout times for web services and tune the queries used with your batch APEX code. The longer the batch size would be, the more likely other job queues will be delayed when too many jobs added together. Here are the best practices to follow by Salesforce Developers:

  • Use batch APEX class only when you have more than one batch of records to execute. If you don’t have enough record sets then you may probably off the batch APEX idea and continue with normal context.
  • Tune SOQL queries together to gather records to be executed as quickly as possible.
  • Try to minimize the total number of asynchronous requests to minimize the chance of delays.
  • Add extra care when planning to invoke a batch job from a trigger. Here, you have to keep in mind that trigger won’t be able to add more batch jobs than the specified governor limits.

salesforce quiz With this discussion, you have covered almost every concept related to batch apex class. Now, you can use it successfully in your next project and don’t forget to define governor limits well otherwise it may be annoying at the end. Today, batch apex class usage is growing tremendously and Salesforce developers are also excited about its benefits.

Read: Salesforce Security Model- What Do You Need To Know?

Salesforce Tutorial Overview


    Janbask Training

    JanBask Training is a leading Global Online Training Provider through Live Sessions. The Live classes provide a blended approach of hands on experience along with theoretical knowledge which is driven by certified professionals.


Trending Courses

AWS

  • AWS & Fundamentals of Linux
  • Amazon Simple Storage Service
  • Elastic Compute Cloud
  • Databases Overview & Amazon Route 53

Upcoming Class

8 days 24 Dec 2019

DevOps

  • Intro to DevOps
  • GIT and Maven
  • Jenkins & Ansible
  • Docker and Cloud Computing

Upcoming Class

-1 day 15 Dec 2019

Data Science

  • Data Science Introduction
  • Hadoop and Spark Overview
  • Python & Intro to R Programming
  • Machine Learning

Upcoming Class

-1 day 15 Dec 2019

Hadoop

  • Architecture, HDFS & MapReduce
  • Unix Shell & Apache Pig Installation
  • HIVE Installation & User-Defined Functions
  • SQOOP & Hbase Installation

Upcoming Class

0 day 16 Dec 2019

Salesforce

  • Salesforce Configuration Introduction
  • Security & Automation Process
  • Sales & Service Cloud
  • Apex Programming, SOQL & SOSL

Upcoming Class

0 day 16 Dec 2019

QA

  • Introduction and Software Testing
  • Software Test Life Cycle
  • Automation Testing and API Testing
  • Selenium framework development using Testing

Upcoming Class

4 days 20 Dec 2019

Business Analyst

  • BA & Stakeholders Overview
  • BPMN, Requirement Elicitation
  • BA Tools & Design Documents
  • Enterprise Analysis, Agile & Scrum

Upcoming Class

0 day 16 Dec 2019

SQL Server

  • Introduction & Database Query
  • Programming, Indexes & System Functions
  • SSIS Package Development Procedures
  • SSRS Report Design

Upcoming Class

4 days 20 Dec 2019

Comments

Search Posts

Reset

Receive Latest Materials and Offers on Salesforce Course

Interviews