Grab Deal : Flat 20% off on live classes + 2 free self-paced courses! - SCHEDULE CALL

- Salesforce Blogs -

The Complete Guide on Asynchronous Apex in Salesforce



Introduction

Asynchronous Apex in Salesforce is a true Savior from the Salesforce governor limits. When there are a limited number of resources available in a multi-tenant architecture, it is hard to decide how to utilize resources to their best limits. So, what should you do when you want to process a huge amount of data together? To avoid this issue or we can say to maximize the resources utilization, the role of asynchronous apex came into the picture.

Salesforce apex classes have introduced the concept of Salesforce asynchronous apex that provides us with a double of the governor limits for almost each software program. Also, it is possible to perform up to 50 million operations on records using asynchronous apex Salesforce. There are multiple Asynchronous apex features in Salesforce and you have to decide which Salesforce asynchronous callout suits your business goals the most. Let us start our guide with asynchronous apex jobs and types of Asynchronous Apex Salesforce CRM. Meanwhile, you can give a quick go through in this in-demand online Salesforce training.

What is an Asynchronous Apex?

In Salesforce Asynchronous apex, the thread will not wait until it completes its tasks before proceeding to next. Instead, it proceeds to next leave it, running in a separate thread. In the Salesforce asynchronous callout, the code runs in multiple threads that help to do many tasks as background jobs offer multiple ways for running your Apex code asynchronously. Moving ahead, you have to choose the asynchronous Apex feature that best suits your needs. 

Types Of Asynchronous Apex Salesforce

Types of Asynchronous Apex Salesforce

  1. Future Methods: It is the basic Asynchronous apex in Salesforce that is used to prevent any delay in a transaction during a web callout.
  2. Batch Apex: This Asynchronous Apex Salesforce feature is used to process multiple records for the job together that require a larger query result.
  3. Queueable Apex: This Asynchronous Apex Salesforce feature is used to schedule the invocation of apex class in Salesforce at the given time.
  4. Scheduled Apex: when one task is dependent on another, we use the scheduled Asynchronous Apex feature. It helps in chaining and complex types of tasks can be completed using scheduled apex features in salesforce.

Moving ahead to Salesforce Asynchronous callout, let us discuss batch apex and future methods in details that are frequently used by Salesforce Developers.

Future Methods in Salesforce Asynchronous Apex

It is the basic Asynchronous apex in Salesforce that is used to prevent any delay in a transaction during a web callout. A future method executes when it has resources available. A future method runs in the background, asynchronously. It is used for executing long-running operations like Web services, call outs or any other operation which has to run on its own time. If Future Annotation is not used in a web service call out, the thread will wait until the response comes and other processes will not be executed. Future methods are used to avoid the mixed DML errors. It is queued and executed when resources are available to. So, it doesn’t have to wait for the completion of a long-running operation. A future method increases the governor limits, such as SOQL query limits and heap size limits. It is defined by @future annotation. Get a better understanding of Salesforce validation rules, with this guide on What Are The Validation Rules? 

@Future:

Future annotation is used to execute methods asynchronously. When you define @Future, it executes when Salesforce has available resources.

@Future (callout = true)

  • Specify the method to make the Salesforce Asynchronous callout to external systems. (E.g. To execute the callout method via an Apex trigger)
  • Note: Methods with the future annotation must be static methods and can only return a void type.
  • Future method parameters must be collections of primitive data types, primitive data types or arrays of primitive data types.
  • Methods with the future annotation cannot take Objects or objects as arguments.

Things to Remember when defining Future asynchronous apex

  • A future annotation must be static methods and return type is only void type.
  • In the future method, the parameter must be collections of primitive data types, primitive data types or arrays of primitive data types; it can't take objects as arguments.
  • It is not necessary that future methods execute in the same order they were called. It is possible that two future methods could run concurrently, which could result in record locking if the two methods were updating the same record.
  • It can’t be used in Visualforce controllers insetMethodName(), getMethodName() nor in the constructor.
  • Neither a future method cannot call from one future method to another future method or it can  invoke a trigger that calls a future method while running a future method
  • The getContent() and getContentAsPDF() methods can’t be used in methods with the future annotation.
  • It is limited to 50 future calls per Apex invocation, and there’s an additional limit on the number of calls in a 24 hour period. You can learn about Salesforce CRM with this CRM guide.

Example

public class DemoFuture { public void insertData(){ DemoFuture.ExampleMethod(); Account acc=new Account(Name='Testing Record',industry='Energy',type='Other',phone='+22-3535543'); insertacc; system.debug(acc); } @future public static void ExampleMethod (){ profile p=[select id,name FROM profile WHERE name='Standard Platform User']; user u =newuser(alias='Gorge',email='Samuel.Gorge@janbask.com', emailencodingkey='UTF-8',lastname='Samuel',languagelocalekey='en_US', localesidkey='en_US',profileid=p.id, timezonesidkey='America/Los_Angeles', userName='Gorge@gmail.com',communityNickName='akash',isactive=false); insert u; system.debug(u); } }

A user insertedWhat is Asynchronous in Salesforce

Record InsertWhat is Asynchronous in Salesforce

What are the Key Advantages of Batch Apex in Salesforce?

  • Batch Apex makes sure that the code stays inside the governor limit in Salesforce whenever a transaction is completed.
  • The subsequent batches won't be executed by Batch Apex until the previous batch has been unsuccessfully executed.
  • Frequently, Batch Apex classes can be used to handle large sets of records.
  • The interface can be programmed to execute batches at predetermined times.
  • Batch Apex classes can implement asynchronous operations.
  • Invoked programmatically and limited to 200 records per batch, batch jobs can work on any size of records during runtime. To better implement it, you can divide a larger record set into batches of 200 records each. 

What is Batch Salesforce Asynchronous Apex?

This Asynchronous Apex Salesforce feature is used to process multiple records for the job together that require a larger query result. Batch Apex is an asynchronous job. Batch apex allows a single job that can be broken into smaller parts, where every record can be processed separately. 

It can process a large number of records with more flexible governor limits than the synchronous code. When a batch class invokes, the job is placed on the Apex job queue and is executed as a separate transaction. When to use Batch Apex?

  • When you want to process a large number of records on a daily basis or even on a specific time of interval then you could go for Batch Apex.
  • Batch Apex is using an interface that must be implemented by the developer. It can be programmatically invoked at runtime. Batch Apex divided total records into small batches of records and processed down to manageable chunks of data.
  • It is used to build complex DML operations for bulk records processes that run on millions of records on the Force.com platform

Syntax: Developers need to define Databases.Batchable Interface

Global class BatchExample implements Database.Batchable{ }

Batch Apex Governor Limits

These are the governor Limits you need to keep in mind when dealing with Batch Salesforce asynchronous apex

  • Up to five queued or active batch jobs are allowed for Apex.
  • Using Database.QueryLocator batch apex returns 50 million records if more than 50 million records are returned.
  • The batch apex Database.execute method can have batches of a maximum number of 2,000, minimum 1 and by default 200 batches.
  • Salesforce chunks the records returned by the start method and then passes each batch to the execute method where governor limits are reset for each execution.
  • The batch apex can implement up to 10 callouts per each batch method.
  • 250,000 is the maximum number of batch executions per 24 hours.
  • Only one batch Apex job's start method can run at a time in an organization. The batch jobs which haven’t started yet remain in the queue until they are started.

Methods in Batch Apex

There are three methods in batch apex

  • Start method
  • Execute method
  • Finish method

Start method

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

  • Using the Database.QueryLocator object increases the query limit by up to 50 million.
  • Use the iterable objects when you have complex criteria to process the records...

Syntax

globalDatabase.QueryLocator start(Database.BatchableContext b){ returnDatabase.getQueryLocator('select id, name from account ); }

Execute Method

The record which returned from start methods is executed into small chunks. Now every batch is separate and runs the execute method.

Global void Execute (Database.BatchableContextb,listacc){ }

Finish Method

This method gets called at the end and you could do some finishing activities like sending an email, calling another batch job. Each execution of a batch Apex job is considered a discrete transaction. For example, a batch Apex job that contains 1,000 records and is executed without the optional scope parameter from Database.executeBatch is considered five transactions of 200 records each. The Apex governor limits are reset for each transaction. If the first transaction succeeds but the second fails, the database updates made in the first transaction are not rolled back. Syntax

Global void finish(Database.BatchableContext b){ }

Example

global class batchExample implements Database.Batchable{ globalDatabase.QueryLocator start(Database.BatchableContext b){ returnDatabase.getQueryLocator('select id, name from account where name=\'United\''); } Global void Execute (Database.BatchableContextb,listacc){ user u=[select id from user where alias='peter']; for(account a:acc){ if(a.industry=='Consulting'){ a.industry='Education'; a.OwnerId=u.id; } } updateacc; } Global void finish(Database.BatchableContext b){ messaging.SingleEmailMessage email1= new messaging.SingleEmailMessage(); string [] toAdd= new string[]{'peter.parker@yahoo.com'}; string [] toBcc= new string[]{'john.janbask@yahoo.com'}; email1.setToAddresses(toadd); // email1.setToAddresses(toBcc); email1.SetSubject('work is completed'); email1.SetSenderDisplayName('JnabaskTraing'); email1.setPlainTextBody('batch apex process is completed'); messaging.Email[]email= new messaging.Email[]{email1}; messaging.sendEmail(email); } } batchExample SS = new batchExample(); Database.executeBatch(SS, 5); system.debug(ss);

What is Asynchronous in Salesforce

Email response

What is Asynchronous in Salesforce

Salesforce Training For Administrators & Developers

  • Personalized Free Consultation
  • Access to Our Learning Management System
  • Access to Our Course Curriculum
  • Be a Part of Our Free Demo Class

Wrapping Up:

We hope this blog gives you a clear idea on why to use an asynchronous apex in Salesforce and how it can be beneficial for your business. The major benefits we noticed are more flexible governor limits in Salesforce asynchronous apex when compared to the synchronous apex code. The concept may be a little tough to understand at first glance but you will practice it quickly with continuous effort and dedication. Before we wrap up, do not forget to check out the online Salesforce training at JanBask Training.

All the Best!

Frequently Asked Questions

Q1. What is Asynchronous Apex in Salesforce? 

Asynchronous Apex is essentially used to run processes later, in another thread. Asynchronous processes do tasks "in the background" without requiring the user to wait for them to be completed.

Q2. What is asynchronous apex in Salesforce syntax?

It is a method or function that runs an action "in the background" so the user doesn't have to wait for it to finish. Asynchronous processes are frequently used for tasks requiring greater limitations, callouts to external systems, and code that must run at a specific time.

Q3. What are types of asynchronous apex in Salesforce?

There are four types of  asynchronous apex in Salesforce:

  • Future Approaches: Execute on their own thread and wait until resources are available before beginning.
  • Run huge projects that would exceed typical processing constraints using Batch Apex.
  • Queueable Apex: similar to future approaches, but allows for more complicated data types and more job chaining.

Q4. What is synchronous and asynchronous apex in Salesforce?

Synchronous refers to something existing or happening simultaneously. Synchronous Apex refers to the execution of all Apex code at once. Asynchronous refers to something that is not present or happening at the same moment. When resources are available, asynchronous apex is run.

Q5. What does it mean to be asynchronous?

Asynchronous, which is pronounced ay-SIHN-kro-nuhs and comes from the Greek words asyn-, which means "not with," and chronos, which means "time," is a broad term used to describe things or occurrences that are not time-coordinated.

Q7. What is Salesforce asynchronous?

First, let's define the Asynchronous process and describe how Salesforce uses it. Requests that don't complete at the same time, but rather one at a time are known as asynchronous processes.

Q8. What distinguishes synchronous communication from asynchronous communication?

What are the primary distinctions? Synchronous means that it occurs simultaneously. Asynchronous means not occurring simultaneously. Participants can receive quick feedback with synchronous learning. Learn more about Salesforce with this basic Salesforce tutorial guide. 

fbicons FaceBook twitterTwitter google+Google+ lingedinLinkedIn pinterest Pinterest emailEmail

     Logo

    JanBask Training

    A dynamic, highly professional, and a global online training course provider committed to propelling the next generation of technology learners with a whole new way of training experience.


  • fb-15
  • twitter-15
  • linkedin-15

Comments

Trending Courses

Cyber Security Course

Cyber Security

  • Introduction to cybersecurity
  • Cryptography and Secure Communication 
  • Cloud Computing Architectural Framework
  • Security Architectures and Models
Cyber Security Course

Upcoming Class

11 days 27 Apr 2024

QA Course

QA

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

Upcoming Class

3 days 19 Apr 2024

Salesforce Course

Salesforce

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

Upcoming Class

2 days 18 Apr 2024

Business Analyst Course

Business Analyst

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

Upcoming Class

11 days 27 Apr 2024

MS SQL Server Course

MS SQL Server

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

Upcoming Class

3 days 19 Apr 2024

Data Science Course

Data Science

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

Upcoming Class

10 days 26 Apr 2024

DevOps Course

DevOps

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

Upcoming Class

-0 day 16 Apr 2024

Hadoop Course

Hadoop

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

Upcoming Class

4 days 20 Apr 2024

Python Course

Python

  • Features of Python
  • Python Editors and IDEs
  • Data types and Variables
  • Python File Operation
Python Course

Upcoming Class

3 days 19 Apr 2024

Artificial Intelligence Course

Artificial Intelligence

  • Components of AI
  • Categories of Machine Learning
  • Recurrent Neural Networks
  • Recurrent Neural Networks
Artificial Intelligence Course

Upcoming Class

11 days 27 Apr 2024

Machine Learning Course

Machine Learning

  • Introduction to Machine Learning & Python
  • Machine Learning: Supervised Learning
  • Machine Learning: Unsupervised Learning
Machine Learning Course

Upcoming Class

3 days 19 Apr 2024

 Tableau Course

Tableau

  • Introduction to Tableau Desktop
  • Data Transformation Methods
  • Configuring tableau server
  • Integration with R & Hadoop
 Tableau Course

Upcoming Class

4 days 20 Apr 2024

Search Posts

Reset

Receive Latest Materials and Offers on Salesforce Course

Interviews