Batch Apex Tutorial Learning Path - Be Productive with [Salesforce]
Batch Apex in Salesforce Tutorial

Batch Apex Tutorial Learning Path – Be Productive with [Salesforce]

Last updated on 08th Jul 2020, Blog, Tutorials

About author

Milan (Salesforce Developer )

Milan is a Salesforce Developer with 4+ years of experience in the VF Pages, Aura components, Apex Triggers, Flows, Apex, Lightning, REST, JavaScript, CSS, and SOQL, LWC, Apex Triggers, and Flows. He spends most of his time researching technology and startups.

(5.0) | 19874 Ratings 1173

Salesforce is a leading CRM (Customer Relationship Management) software which is served form cloud. It has more than 800 applications to support various features like generating new leads, acquiring new leads, increasing sales and closing the deals. It is designed to manage the organization’s data focused on customer and sales details. It also offers features to customize its inbuilt data structures and GUI to suit the specific needs of a business. More recently, it has started offering the IOT (internet of things) connectivity to the CRM platform.

In this chapter, we will understand Batch Processing in Apex. Consider a scenario wherein, we will process large number of records on daily basis, probably the cleaning of data or maybe deleting some unused data.

For business scenarios which require the platform to process more than 50000 records, Batch Apex comes to the rescue. Batch Apex facilitates asynchronous processing of the records in multiple batches or chunks and is straightforward to implement for a developer.

Salesforce started as a cloud based solution for CRM. CRM stands for Customer Relationship Management. It involves managing all aspects of relationship between an organization and its customers. For example, the contact details of the customer, the deals that are in progress or already completed, the support requests from a customer or a new lead from a new customer. Beyond the customer related information, it also involves storing and managing the details of the people and the concerned department from the seller organization that is managing the customer’s account and needs. This makes it easy to manage and enhance the relationship with the customer and hence better growth for the organization.

Following are the different features of the Salesforce platform −

Contact Management

To view customer contact details, activity history, customer communications, and internal account discussions, etc. In short, it manages all the data pertaining to the contact with a customer.

Opportunity Management

It provides the details of the stage a deal is in, the products involved in the deal, the quotation for the deal etc. In short it manages all the data that helps in identifying, progressing and closing a deal.

Salesforce Engage

This feature is focused on making personalized contact with a customer for various campaigns designed by the marketing team. It also provides real-time sales alerts based on the level of engagement with a customer.

Sales Collaboration

This feature helps in quickly finding experts who can help in closing a deal based on customer queries and feedback. In short, it helps in bringing in a collaborative effort to engage an entire team in the deal and make the deal happen.

Sales Performance Management

It provides a metric-based goal setting, and also continuous feedback and rewards and recognition for the sales team. This helps in enhancing the performance of the sales team.

Lead Management

This feature initiates and tracks the leads that are in progress. It also helps in continually optimizing campaigns across every channel.

Partner Management

This feature helps in building a community with partners. It also helps in connecting directly with channel partners to share goals, objectives, and activities.

Salesforce Mobile App

This is the mobile platform to carry out all the above activities on a mobile platform.

Workflow and Approvals

It is a visual design to automate the business processes. The interface provides simple drag and drop options to make this design. It helps in creating a flexible approval process with deal discounts and expense management etc.

Email Integration

Salesforce can integrate to an existing email platform. This helps in providing flexibility to the existing team with no additional learning curve.

Files Sync and Share

This feature provides the sales team the power to easily share various files, discuss them and update them as needed. Also receive alerts when something in the file changes.

Reports and Dashboards

Dashboards offer a real-time picture of the business at a glance. With this, anyone can create detailed reports which can be accessed from anywhere.

    Subscribe For Free Demo

    [custom_views_post_title]

    Sales Forecasting

    This feature helps in getting a real time view of the forecast of a sales team. It provides multi-currency support and an in-line editing mode to manage the sales forecast well.

    Territory Management

    This feature is used to create multiple territory models, preview them before rollout, and continually optimize and balance territories throughout the year.

    Following are the different features of the Salesforce platform −

    What is Batch Apex?

    Batch Apex is asynchronous execution of Apex code, specially designed for processing the large number of records and has greater flexibility in governor limits than the synchronous code.

    When to use Batch Apex?

    • When you want to process large number of records on daily basis or even on specific time of interval then you can go for Batch Apex.
    • Also, when you want an operation to be asynchronous then you can implement the Batch Apex. Batch Apex is exposed as an interface that must be implemented by the developer. Batch jobs can be programmatically invoked at runtime using Apex. Batch Apex operates over small batches of records, covering your entire record set and breaking the processing down to manageable chunks of data.

    Using Batch Apex

    When we are using the Batch Apex, we must implement the Salesforce-provided interface Database.Batchable, and then invoke the class programmatically.

    You can monitor the class by following these steps −

    To monitor or stop the execution of the batch Apex Batch job, go to Setup → Monitoring → Apex Jobs or Jobs → Apex Jobs.

    Batch-Apex
    Batch-Apex-jobs

    What is a Batchable Interface? 

    To use Batch Apex, you must implement “Database.Batchable”. This interface has three methods. those are:

    Batchable interface has the following three methods that need to be implemented −

    • Start
    • Execute
    • Finish

    Let us now understand each method in detail.

    Start

    Start method is automatically called at the beginning of the apex job. This method will collect record or objects on which the operation should be performed. These records are divided into subtasks and pass those to execute method.

    The Start method is one of the three methods of the Database.Batchable interface.

    Syntax

    • global void execute(Database.BatchableContext BC, list<sobject<) {}

    This method will be called at the starting of the Batch Job and collects the data on which the Batch job will be operating.

    Consider the following points to understand the method −

    • Use the Database.QueryLocator object when you are using a simple query to generate the scope of objects used in the batch job. In this case, the SOQL data row limit will be bypassed.
    • Use the iterable object when you have complex criteria to process the records. Database.QueryLocator determines the scope of records which should be processed.

    Execute

    Execute Method performs an operation which we want to perform on the records fetched from start method.

    Let us now understand the Execute method of the Database.Batchable interface.

    Syntax

    • global void execute(Database.BatchableContext BC, list<sobject<) {}

    where, list<sObject< is returned by the Database.QueryLocator method.

    This method gets called after the Start method and does all the processing required for Batch Job.

    Finish

    Finish method executes after all batches are processed. Use this method to send confirmation email notifications.

    We will now discuss the Finish method of the Database.Batchable interface.

    Syntax

    • global void finish(Database.BatchableContext BC) {}

    This method gets called at the end and you can do some finishing activities like sending an email with information about the batch job records processed and status.

    Limitations

    We can only have 5 batch job processing at a time. This is one of the limitations of Batch Apex.

    Scheduling the Apex Batch Job using Apex Detail Page

    You can schedule the Apex class via Apex detail page as given below −

    Step 1 − Go to Setup ⇒ Apex Classes, Click on Apex Classes.

    Course Curriculum

    Join Salesforce Training Course with Global Recognised Certification

    Weekday / Weekend BatchesSee Batch Details
    Apex-Classes

    Step 2 − Click on the Schedule Apex button.

    Schedule-Apex

    Step 3 − Provide details.

    Schedule-Apex-details

    Implementing Batch Apex

    Batch Apex implements the Database.batchable interface. The interface has Start(), Execute() and Finish() methods which should be implemented in the Batch Apex class.

    Startmethod: 

    Start method is a collection point for the records to be processed in the execute method of the batch apex.

    Execute method: 

    The actual processing of the records takes place in the execute method.

    Finish method: 

    Finish methods can have post job processing actions like sending the emails or it can also be used to chain another batch class.

    Scheduling the Batch Apex

    Method 1: Using OOTB Schedule Apex functionality

    Steps:

    • Click on Setup and search for Apex Classes in the quick find box.
    • Click on the Schedule Apex button at the top panel.
    Schedule-Apex-steps

    3. Fill in the information on the Schedule Apex record page and Save. The apex class should be the Scheduler class implementing the executebatch(batch) method.

    apex-class

    Method 2:  Invoking Batch Class via Schedulable Apex:

    Course Curriculum

    Learn Salesforce Training to Advance Your Career with Expert-led Course

    • Instructor-led Sessions
    • Real-life Case Studies
    • Assignments
    Explore Curriculum

    The Apex class should be created which should implement the Schedulable apex. The Schedulable apex must implement System.Schedule() method to enqueue the batch apex in the execution queue. The System.Schedule() method expects three arguments viz Job Name, Cron expression for the batch schedule and the batch class name.

    Batch Apex Chaining

    With the onset of API version 29.0 and after, a batch class can be chained to another batch class. Chaining of batch apex kickstarts the execution of the chained batch class once the execution of the base batch class is finished. At maximum, only 5 Batch jobs can be chained to one another. 

    Optimizing Your Implementation

    • Batch Apex jobs run faster when the startmethod returns a QueryLocator object that doesn’t include related records via a subquery. Avoiding relationship subqueries in a QueryLocator allows batch jobs to run using a faster, chunked implementation.
    • To ensure fast execution of batch jobs, minimize Web service callout times and tune queries used in your batch Apex code.
    • For each 10,000 AsyncApexJobrecords, Apex creates an AsyncApexJob record of type BatchApexWorker for internal use. When querying for all AsyncApexJob records, we recommend that you filter out records of type BatchApexWorker using the JobType
    • For a sharing recalculation, we recommend that the execute method delete and then re-create all Apex managed sharing for the records in the batch. This process ensures that sharing is accurate and complete.
    • Use the Test methods startTest and stopTest around the executeBatch method to ensure that it finishes before continuing your test.

    Governor Limits for Batch Apex

    • Before writing the batch apex code, you need to consider the governor’s execution limits to ensure the efficient use of classes.
    • It allows the maximum of five active or queued batch jobs for Apex.
    • One user can open up to 50 query cursors for a certain duration. If the user tries to open a new one, the oldest 50 cursors will be released.

    Advantage of using batch Apex

    • Every transaction starts with a new set of governor limits, making it easier to ensure that your code stays within the governor execution limits.
    • If one batch fails to process successfully, all other successful batch transactions aren’t rolled back
    • For each transaction, Batch Apex ensures that the code stays within the governor limit.
    • Batch Apex won’t execute or even consider executing the other batches of records, until and unless the one batch is not successfully executed.
    • A comprehensive set of records can be executed together using Batch Apex classes.
    • The interface can be scheduled for batch execution at different periods.
    • Asynchronous operations can be implemented through Batch Apex classes.
    • Batch Jobs are invoked programmatically at run time (during the execution process) and can be operated on any size of records, with a maximum of 200 batch records. You can split larger record data into 200 records per batch for better performance.

    Salesforce Sample Resumes! Download & Edit, Get Noticed by Top Employers! Download

    Conclusion

    Batch Apex is used to operate a high volume of records and it allows you to run the code at a certain duration. With Batch Apex, you can process records asynchronously in batches. It allows you to split records into multiple batches to execute them separately. 

    As with future methods, there are a few things you want to keep in mind when using Batch Apex. To ensure fast execution of batch jobs, minimize Web service callout times and tune queries used in your batch Apex code. The longer the batch job executes, the more likely other queued jobs are delayed when many jobs are in the queue. Best practices include:

    • Only use Batch Apex if you have more than one batch of records. If you don’t have enough records to run more than one batch, you are probably better off using Queueable Apex.
    • Tune any SOQL query to gather the records to execute as quickly as possible.
    • Minimize the number of asynchronous requests created to minimize the chance of delays.
    • Use extreme care if you are planning to invoke a batch job from a trigger. You must be able to guarantee that the trigger won’t add more batch jobs than the limit.

    Are you looking training with Right Jobs?

    Contact Us
    Get Training Quote for Free