SlideShare a Scribd company logo
5
Most read
9
Most read
12
Most read
What is synchronous & asynchronous?
When you execute something synchronously, you wait for it to finish before moving on to another task.
When you execute something asynchronously, you can move on to another task before it finishes.
Simple code example
private void example(){
System.debug("Before call");
doSomething();
System.debug("After call");
}
private void doSomething(){
System.debug("In call");
}
This will always output:
Before call
In call
After call
But if we were to make doSomething asynchronous (multiple ways to do it), then the output could become:
Before call
After call
In call
Asynchronous Apex features and when to use each:
Asynchronous Apex Feature When to Use
Future Methods • When you have a long-running method and need to prevent delaying an Apex
transaction
• When you make callouts to external Web services
• To segregate DML operations and bypass the mixed save DML error
Queueable Apex • To start a long-running operation and get an ID for it
• To pass complex types to a job
• To chain jobs
Batch Apex • For long-running jobs with large data volumes that need to be performed in batches,
such as database maintenance jobs
• For jobs that need larger query results than regular transactions allow
Scheduled Apex • To schedule an Apex class to run on a specific schedule
Continuations • Asynchronous Callouts to a SOAP or REST Web service from Visualforce Pages
New features in future method
1. Run Future Methods with Higher Limits. One of the following limits can be doubled or tripled for each future method.
• Heap size
• CPU timeout
• Number of SOQL queries
• Number of DML statements issued
• Number of records that were processed as a result of DML operations, Aprroval.process, or Database.emptyRecycleBin.
Ex: @future(limits='2x|3xlimitName').
2. The execution limits of future methods and callouts in an Apex transaction have increased to 50 methods and 100
callouts respectively.
Ex:
1. Trigger CreateGroupMember on Account.
2. Trigger Create community user on Account.
Queueable interface is new kid on the async block
Take control of our asynchronous Apex processes by using the Queueable interface. This interface enables us to add jobs
to the queue and monitor them, which is an enhanced way of running your asynchronous Apex code compared to using
future methods.
And here is list of limits from Queueable Apex vs Future methods:
Queueable Future Methods
The execution of a queued job counts once against the
shared limit for asynchronous Apex method executions.
Same
You can add up to 50 jobs to the queue with
System.enqueueJob in a single transaction.
No more than 50 method calls per Apex invocation.
The maximum stack depth for chained jobs is two, which
means that you can have a maximum of two jobs in the
chain.
A future method can’t invoke another future method.
When chaining jobs, you can add only one job from an
executing job with System.enqueueJob.
Methods with the future annotation cannot take sObjects
or objects as arguments.
Queueable Example:
public class AsyncExecutionExample implements Queueable {
public void execute( QueueableContext context) {
Account a = new Account(Name='Acme',Phone='(415) 555-1212');
insert a;
}
}
To add this class as a job on the queue, call this method:
ID jobID = System.enqueueJob(new AsyncExecutionExample());
To query information about your submitted job, perform a SOQL query on AsyncApexJob by filtering on the job ID that the
System.enqueueJob method returns. This example uses the jobID variable that was obtained in the previous example.
AsyncApexJob jobInfo = [SELECT Status,NumberOfErrors FROM AsyncApexJob WHERE Id=:jobID];
Queueable Example:
Chaining Jobs
If we need to run a job after some other processing is done first by another job, we can chain queueable jobs. To chain a job
to another job, submit the second job from the execute() method of your queueable class. You can add only one job from an
executing job.
public class AsyncExecutionExample implements Queueable {
public void execute( QueueableContext context) {
// Your processing logic here
// Chain this job to next job by submitting the next job
System.enqueueJob(new SecondJob());
}
}
Note: We can’t chain queueable jobs in an Apex test. Doing so results in an error. To avoid getting an error, you can check if
Apex is running in test context by calling Test.isRunningTest() before chaining jobs.
To better explain this, consider the following scenario. In a system, process 1 would update all the Accounts where Type
picklist is empty to “Technology Partner”, and process 2 needs to look at all Accounts where Type picklist is “Technology
Partner” and update all the related Opportunities for those Accounts where Stage picklist is empty to “Prospecting”. The
process 2 needs to execute once the process 1 is completed only.
Batch Apex
• Advantages
1. It can process up to 50m records
2. It can be scheduled to run at a particular time
3. Asynchronous processing
• Disadvantages
1. Only 5 concurrent batch jobs running at a time
2. It’s difficult to troubleshoot
3. Execution may be delayed based on server availability
4. @future methods are not allowed
5. Can’t use getContent/getContentAsPDF methods
6. and a few more governor limits…
Holding Batch Jobs in the Apex Flex Queue
With Apex Flex Queue, you can submit up to 100 batch jobs without getting an error.
• The batch job is placed in the Apex flex queue, and its status is set to Holding.
• If the Apex flex queue has the maximum number of 100 jobs, Database.executeBatch throws a LimitException and
doesn’t add the job to the queue.
Reordering Jobs in the Apex Flex Queue:
While submitted jobs have a status of Holding, we can reorder them in the Salesforce user interface to control which batch
jobs are processed first. To do so, from Setup, click Jobs | Apex Flex Queue.
Still the system can process up to five queued or active jobs simultaneously for each organization.
Now we are here:
Batchable @future Queueable
- Good at processing large number of
records (50m).
- Can be scheduled to run at a certain
time
- Maximum of 5 concurrent jobs
running at a time
- You need good error handling for
troubleshooting
- Quick async processing (typically 1
record at a time) e.g. avoid mixed
DML or a web service callout
- Faster than a Batch
- Easy to implement
- Only accepts primitive type
arguments
- Can’t chain jobs
- Hard to monitor
- Quick async processing that
supports primitive types
- Faster than a batch
- Ability to chain jobs
- Can’t have more than 1 job doing
callouts within the chain
- Can be monitored
Continuation object in Apex - Asynchronous callouts for long running request
We may run into scenario in Salesforce project, where we need call external web service but no need
to wait for response. Response from external web service can be processed asynchronously and once
processed it can be presented in Visualforce page.
Execution Flow of an Asynchronous Callout
We can accomplish this by using Actionsupport or Javascript remoting. However, this is possible with
using Continuation method as well. In Continuation approach, we can call external web service and
inform that which callback method should be used to process response. After execution of callback
method, data is presented in visualforce page.
Ex:-
Thank you

More Related Content

PPTX
Salesforce Development Best Practices
PDF
Best Practices with Apex in 2022.pdf
PDF
Introduction to Apex Triggers
PPTX
Introduction to Apex for Developers
PDF
Apex Enterprise Patterns: Building Strong Foundations
PDF
Designing Salesforce Platform Events
PPTX
Integrating with salesforce
Salesforce Development Best Practices
Best Practices with Apex in 2022.pdf
Introduction to Apex Triggers
Introduction to Apex for Developers
Apex Enterprise Patterns: Building Strong Foundations
Designing Salesforce Platform Events
Integrating with salesforce

What's hot (20)

PPTX
Episode 19 - Asynchronous Apex - Batch apex & schedulers
PPTX
Batch Apex in Salesforce
PDF
Build Reliable Asynchronous Code with Queueable Apex
PDF
All About Test Class in #Salesforce
PPTX
Apex code (Salesforce)
PPTX
Episode 20 - Trigger Frameworks in Salesforce
PPTX
Asynchronous Apex Salesforce World Tour Paris 2015
PPTX
Batchable vs @future vs Queueable
PDF
Flow in Salesforce
PDF
Apex Testing Best Practices
PPT
Salesforce REST API
PPTX
Approval Process in Salesforce
PPT
Salesforce Presentation
PPT
Salesforce Integration
PDF
Replicate Salesforce Data in Real Time with Change Data Capture
PPTX
Salesforce Integration Pattern Overview
PDF
Architecting Multi-Org Solutions
PDF
Introduction to the Salesforce Security Model
PPTX
Real Time Integration with Salesforce Platform Events
PDF
Lightning web components episode 2- work with salesforce data
Episode 19 - Asynchronous Apex - Batch apex & schedulers
Batch Apex in Salesforce
Build Reliable Asynchronous Code with Queueable Apex
All About Test Class in #Salesforce
Apex code (Salesforce)
Episode 20 - Trigger Frameworks in Salesforce
Asynchronous Apex Salesforce World Tour Paris 2015
Batchable vs @future vs Queueable
Flow in Salesforce
Apex Testing Best Practices
Salesforce REST API
Approval Process in Salesforce
Salesforce Presentation
Salesforce Integration
Replicate Salesforce Data in Real Time with Change Data Capture
Salesforce Integration Pattern Overview
Architecting Multi-Org Solutions
Introduction to the Salesforce Security Model
Real Time Integration with Salesforce Platform Events
Lightning web components episode 2- work with salesforce data
Ad

Viewers also liked (20)

PPTX
Governor limits
PDF
Design Patterns for Asynchronous Apex
PDF
Process builder vs Triggers
PDF
Advanced Apex Development - Asynchronous Processes
PPTX
Apex Flex Queue: Batch Apex Liberated
PPTX
Salesforce Process builder Vs Workflows
PPTX
Salesforce DUG - Queueable Apex
PPTX
Salesforce Apex Ten Commandments
PDF
Enterprise Integration - Solution Patterns From the Field
PPTX
Using the Tooling API to Generate Apex SOAP Web Service Clients
PDF
Apex Nirvana
PPTX
Spring '16 release belgium salesforce user group samuel de rycke
PPTX
Salesforce APIs
PPTX
Using Apex for REST Integration
PPTX
Integrate with External Systems using Apex Callouts
PPTX
Dive Deep into Apex: Advanced Apex!
PPTX
Salesforce1 API Overview
PPTX
Webinar: Integrating Salesforce and Slack (05 12-16)
PPT
The Importance of Integration to Salesforce Success
PDF
Secure Salesforce: External App Integrations
Governor limits
Design Patterns for Asynchronous Apex
Process builder vs Triggers
Advanced Apex Development - Asynchronous Processes
Apex Flex Queue: Batch Apex Liberated
Salesforce Process builder Vs Workflows
Salesforce DUG - Queueable Apex
Salesforce Apex Ten Commandments
Enterprise Integration - Solution Patterns From the Field
Using the Tooling API to Generate Apex SOAP Web Service Clients
Apex Nirvana
Spring '16 release belgium salesforce user group samuel de rycke
Salesforce APIs
Using Apex for REST Integration
Integrate with External Systems using Apex Callouts
Dive Deep into Apex: Advanced Apex!
Salesforce1 API Overview
Webinar: Integrating Salesforce and Slack (05 12-16)
The Importance of Integration to Salesforce Success
Secure Salesforce: External App Integrations
Ad

Similar to Salesforce asynchronous apex (20)

PPTX
Asynchronous Apex .pptx
PPTX
SFDC Batch Apex
PPTX
Apex Liberation - the evolution of Flex Queue (DF15)
PDF
Apex Liberation: The Evolution of FlexQueues
PDF
Continuation_alan_20220503.pdf
PPTX
Salesforce Summer 14 Release
PPTX
SFDC Introduction to Apex
PDF
Hyperbatch (LoteRapido) - Punta Dreamin' 2017
PDF
Batch Jobs: Beyond the Basics
PPTX
Episode 18 - Asynchronous Apex
PPTX
Salesforce Apex Hours :- Hyper batch
TXT
Salesforce integration questions
PPTX
Integration study group 2: Patterns
PPT
Development withforce
PPTX
ELEVATE Paris
PPT
Salesforce1 Platform for programmers
PDF
Salesforce app limits_cheatsheet latest by 25 oct 2019
PDF
Apex Nuances: Transitioning to Force.com Development
PDF
Technical Webinar: Patterns for Integrating Your Salesforce App with Off-Plat...
PPTX
Advanced Apex Webinar
Asynchronous Apex .pptx
SFDC Batch Apex
Apex Liberation - the evolution of Flex Queue (DF15)
Apex Liberation: The Evolution of FlexQueues
Continuation_alan_20220503.pdf
Salesforce Summer 14 Release
SFDC Introduction to Apex
Hyperbatch (LoteRapido) - Punta Dreamin' 2017
Batch Jobs: Beyond the Basics
Episode 18 - Asynchronous Apex
Salesforce Apex Hours :- Hyper batch
Salesforce integration questions
Integration study group 2: Patterns
Development withforce
ELEVATE Paris
Salesforce1 Platform for programmers
Salesforce app limits_cheatsheet latest by 25 oct 2019
Apex Nuances: Transitioning to Force.com Development
Technical Webinar: Patterns for Integrating Your Salesforce App with Off-Plat...
Advanced Apex Webinar

Salesforce asynchronous apex

  • 1. What is synchronous & asynchronous? When you execute something synchronously, you wait for it to finish before moving on to another task. When you execute something asynchronously, you can move on to another task before it finishes.
  • 2. Simple code example private void example(){ System.debug("Before call"); doSomething(); System.debug("After call"); } private void doSomething(){ System.debug("In call"); } This will always output: Before call In call After call But if we were to make doSomething asynchronous (multiple ways to do it), then the output could become: Before call After call In call
  • 3. Asynchronous Apex features and when to use each: Asynchronous Apex Feature When to Use Future Methods • When you have a long-running method and need to prevent delaying an Apex transaction • When you make callouts to external Web services • To segregate DML operations and bypass the mixed save DML error Queueable Apex • To start a long-running operation and get an ID for it • To pass complex types to a job • To chain jobs Batch Apex • For long-running jobs with large data volumes that need to be performed in batches, such as database maintenance jobs • For jobs that need larger query results than regular transactions allow Scheduled Apex • To schedule an Apex class to run on a specific schedule Continuations • Asynchronous Callouts to a SOAP or REST Web service from Visualforce Pages
  • 4. New features in future method 1. Run Future Methods with Higher Limits. One of the following limits can be doubled or tripled for each future method. • Heap size • CPU timeout • Number of SOQL queries • Number of DML statements issued • Number of records that were processed as a result of DML operations, Aprroval.process, or Database.emptyRecycleBin. Ex: @future(limits='2x|3xlimitName'). 2. The execution limits of future methods and callouts in an Apex transaction have increased to 50 methods and 100 callouts respectively. Ex: 1. Trigger CreateGroupMember on Account. 2. Trigger Create community user on Account.
  • 5. Queueable interface is new kid on the async block Take control of our asynchronous Apex processes by using the Queueable interface. This interface enables us to add jobs to the queue and monitor them, which is an enhanced way of running your asynchronous Apex code compared to using future methods. And here is list of limits from Queueable Apex vs Future methods: Queueable Future Methods The execution of a queued job counts once against the shared limit for asynchronous Apex method executions. Same You can add up to 50 jobs to the queue with System.enqueueJob in a single transaction. No more than 50 method calls per Apex invocation. The maximum stack depth for chained jobs is two, which means that you can have a maximum of two jobs in the chain. A future method can’t invoke another future method. When chaining jobs, you can add only one job from an executing job with System.enqueueJob. Methods with the future annotation cannot take sObjects or objects as arguments.
  • 6. Queueable Example: public class AsyncExecutionExample implements Queueable { public void execute( QueueableContext context) { Account a = new Account(Name='Acme',Phone='(415) 555-1212'); insert a; } } To add this class as a job on the queue, call this method: ID jobID = System.enqueueJob(new AsyncExecutionExample()); To query information about your submitted job, perform a SOQL query on AsyncApexJob by filtering on the job ID that the System.enqueueJob method returns. This example uses the jobID variable that was obtained in the previous example. AsyncApexJob jobInfo = [SELECT Status,NumberOfErrors FROM AsyncApexJob WHERE Id=:jobID];
  • 7. Queueable Example: Chaining Jobs If we need to run a job after some other processing is done first by another job, we can chain queueable jobs. To chain a job to another job, submit the second job from the execute() method of your queueable class. You can add only one job from an executing job. public class AsyncExecutionExample implements Queueable { public void execute( QueueableContext context) { // Your processing logic here // Chain this job to next job by submitting the next job System.enqueueJob(new SecondJob()); } } Note: We can’t chain queueable jobs in an Apex test. Doing so results in an error. To avoid getting an error, you can check if Apex is running in test context by calling Test.isRunningTest() before chaining jobs. To better explain this, consider the following scenario. In a system, process 1 would update all the Accounts where Type picklist is empty to “Technology Partner”, and process 2 needs to look at all Accounts where Type picklist is “Technology Partner” and update all the related Opportunities for those Accounts where Stage picklist is empty to “Prospecting”. The process 2 needs to execute once the process 1 is completed only.
  • 8. Batch Apex • Advantages 1. It can process up to 50m records 2. It can be scheduled to run at a particular time 3. Asynchronous processing • Disadvantages 1. Only 5 concurrent batch jobs running at a time 2. It’s difficult to troubleshoot 3. Execution may be delayed based on server availability 4. @future methods are not allowed 5. Can’t use getContent/getContentAsPDF methods 6. and a few more governor limits…
  • 9. Holding Batch Jobs in the Apex Flex Queue With Apex Flex Queue, you can submit up to 100 batch jobs without getting an error. • The batch job is placed in the Apex flex queue, and its status is set to Holding. • If the Apex flex queue has the maximum number of 100 jobs, Database.executeBatch throws a LimitException and doesn’t add the job to the queue. Reordering Jobs in the Apex Flex Queue: While submitted jobs have a status of Holding, we can reorder them in the Salesforce user interface to control which batch jobs are processed first. To do so, from Setup, click Jobs | Apex Flex Queue. Still the system can process up to five queued or active jobs simultaneously for each organization.
  • 10. Now we are here: Batchable @future Queueable - Good at processing large number of records (50m). - Can be scheduled to run at a certain time - Maximum of 5 concurrent jobs running at a time - You need good error handling for troubleshooting - Quick async processing (typically 1 record at a time) e.g. avoid mixed DML or a web service callout - Faster than a Batch - Easy to implement - Only accepts primitive type arguments - Can’t chain jobs - Hard to monitor - Quick async processing that supports primitive types - Faster than a batch - Ability to chain jobs - Can’t have more than 1 job doing callouts within the chain - Can be monitored
  • 11. Continuation object in Apex - Asynchronous callouts for long running request We may run into scenario in Salesforce project, where we need call external web service but no need to wait for response. Response from external web service can be processed asynchronously and once processed it can be presented in Visualforce page. Execution Flow of an Asynchronous Callout We can accomplish this by using Actionsupport or Javascript remoting. However, this is possible with using Continuation method as well. In Continuation approach, we can call external web service and inform that which callback method should be used to process response. After execution of callback method, data is presented in visualforce page. Ex:-