Our Support: During the COVID-19 outbreak, we request learners to CALL US for Special Discounts!

- Salesforce Blogs -

What is Asynchronous Apex in Salesforce?

Introduction

Asynchronous Apex in Salesforce is a true Savior from the Salesforce governor limits. Everybody knows how complex are governor limits in Salesforce. 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 discussion with asynchronous apex jobs and types of Asynchronous Apex Salesforce CRM.

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, runs 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. 

Learn Salesforce in the Easiest Way

  • Learn from the videos
  • Learn anytime anywhere
  • Pocket-friendly mode of learning
  • Complimentary eBook available

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 at the given time.
  4. Scheduled Apex: when one task is dependent on another, we use schedule 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.

Read: What is Salesforce Workbench? Salesforce Workbench Tutorial Guide

@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 anther 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 limited to 50 future calls per Apex invocation, and there’s an additional limit on the number of calls in a 24 hours period.

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='[email protected]',
emailencodingkey='UTF-8',lastname='Samuel',languagelocalekey='en_US',
localesidkey='en_US',profileid=p.id, timezonesidkey='America/Los_Angeles',
userName='[email protected]',communityNickName='akash',isactive=false);

insert u;
system.debug(u);

 }
}

A user inserted What is Asynchronous in Salesforce Record Insert What is Asynchronous in Salesforce

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 processing 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

Salesforce Training For Administrators & Developers

Read: How Can I Start my Career in the Salesforce Industry?
  • No cost for a Demo Class
  • Industry Expert as your Trainer
  • Available as per your schedule
  • Customer Support Available

Syntax: Developers need to define Databases.Batchable Interface


Global class BatchExample implements Database.Batchable<sObject>{
}

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 of executing.
  • 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 runs the execute method.


Global void Execute (Database.BatchableContextb,list&lt;sObject&gt;acc){

}

Finish Method

This method gets called at the end and you could do some finishing activities like sending an email, call 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

Read: Salesforce Training & Certification Cost for Admin, Developer

Global void finish(Database.BatchableContext b){

}

Example


global class batchExample  implements Database.Batchable&lt;sobject&gt;{

globalDatabase.QueryLocator start(Database.BatchableContext b){

returnDatabase.getQueryLocator('select id, name from account where name=\'United\'');

}

Global void Execute (Database.BatchableContextb,list&lt;account&gt;acc){

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[]{'[email protected]'};

string [] toBcc= new string[]{'[email protected]'};

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:

This blog gives you a clear idea of 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. All the Best!




    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.


Comments

Trending Courses

AWS

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

Upcoming Class

8 days 23 Jul 2020

DevOps

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

Upcoming Class

1 day 16 Jul 2020

Data Science

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

Upcoming Class

1 day 16 Jul 2020

Hadoop

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

Upcoming Class

2 days 17 Jul 2020

Salesforce

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

Upcoming Class

-0 day 15 Jul 2020

QA

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

Upcoming Class

9 days 24 Jul 2020

Business Analyst

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

Upcoming Class

2 days 17 Jul 2020

MS SQL Server

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

Upcoming Class

-0 day 15 Jul 2020

Python

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

Upcoming Class

8 days 23 Jul 2020

Artificial Intelligence

  • Components of AI
  • Categories of Machine Learning
  • Recurrent Neural Networks
  • Recurrent Neural Networks

Upcoming Class

5 days 20 Jul 2020

Machine Learning

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

Upcoming Class

2 days 17 Jul 2020

Tableau

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

Upcoming Class

2 days 17 Jul 2020

Search Posts

Reset

Receive Latest Materials and Offers on Salesforce Course

Interviews