SlideShare une entreprise Scribd logo
1  sur  12
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

Contenu connexe

Tendances

Salesforce DUG - Queueable Apex
Salesforce DUG - Queueable ApexSalesforce DUG - Queueable Apex
Salesforce DUG - Queueable ApexAkshay Varu
 
salesforce triggers interview questions and answers
salesforce triggers interview questions and answerssalesforce triggers interview questions and answers
salesforce triggers interview questions and answersbhanuadmob
 
Lwc presentation
Lwc presentationLwc presentation
Lwc presentationNithesh N
 
Managing Your Batch and Scheduled Apex Processes with Relax
Managing Your Batch and Scheduled Apex Processes with RelaxManaging Your Batch and Scheduled Apex Processes with Relax
Managing Your Batch and Scheduled Apex Processes with RelaxSalesforce Developers
 
Best Practices for RESTful Web Services
Best Practices for RESTful Web ServicesBest Practices for RESTful Web Services
Best Practices for RESTful Web ServicesSalesforce Developers
 
Visualforce & Force.com Canvas: Unlock your Web App inside of Salesforce.com ...
Visualforce & Force.com Canvas: Unlock your Web App inside of Salesforce.com ...Visualforce & Force.com Canvas: Unlock your Web App inside of Salesforce.com ...
Visualforce & Force.com Canvas: Unlock your Web App inside of Salesforce.com ...Salesforce Developers
 
Why Flow with Salesforce Flow
Why Flow with Salesforce FlowWhy Flow with Salesforce Flow
Why Flow with Salesforce FlowAjeet Singh
 
Two-Way Integration with Writable External Objects
Two-Way Integration with Writable External ObjectsTwo-Way Integration with Writable External Objects
Two-Way Integration with Writable External ObjectsSalesforce Developers
 
REST API Design & Development
REST API Design & DevelopmentREST API Design & Development
REST API Design & DevelopmentAshok Pundit
 
Salesforce Integration Patterns
Salesforce Integration PatternsSalesforce Integration Patterns
Salesforce Integration Patternsusolutions
 
Apex Enterprise Patterns: Building Strong Foundations
Apex Enterprise Patterns: Building Strong FoundationsApex Enterprise Patterns: Building Strong Foundations
Apex Enterprise Patterns: Building Strong FoundationsSalesforce Developers
 
Asynchronous Apex Salesforce World Tour Paris 2015
Asynchronous Apex Salesforce World Tour Paris 2015Asynchronous Apex Salesforce World Tour Paris 2015
Asynchronous Apex Salesforce World Tour Paris 2015Samuel De Rycke
 
Advanced Apex Development - Asynchronous Processes
Advanced Apex Development - Asynchronous ProcessesAdvanced Apex Development - Asynchronous Processes
Advanced Apex Development - Asynchronous ProcessesSalesforce Developers
 
Salesforce Development Best Practices
Salesforce Development Best PracticesSalesforce Development Best Practices
Salesforce Development Best PracticesVivek Chawla
 
Salesforce integration best practices columbus meetup
Salesforce integration best practices   columbus meetupSalesforce integration best practices   columbus meetup
Salesforce integration best practices columbus meetupMuleSoft Meetup
 
Apex trigger framework Salesforce #ApexTrigger #Salesforce #SFDCPanther
Apex trigger framework Salesforce #ApexTrigger #Salesforce #SFDCPantherApex trigger framework Salesforce #ApexTrigger #Salesforce #SFDCPanther
Apex trigger framework Salesforce #ApexTrigger #Salesforce #SFDCPantherAmit Singh
 
Intro to Force.com Canvas: Running External Apps within the Salesforce UI Web...
Intro to Force.com Canvas: Running External Apps within the Salesforce UI Web...Intro to Force.com Canvas: Running External Apps within the Salesforce UI Web...
Intro to Force.com Canvas: Running External Apps within the Salesforce UI Web...Salesforce Developers
 

Tendances (20)

Salesforce DUG - Queueable Apex
Salesforce DUG - Queueable ApexSalesforce DUG - Queueable Apex
Salesforce DUG - Queueable Apex
 
SFDC Batch Apex
SFDC Batch ApexSFDC Batch Apex
SFDC Batch Apex
 
Apex Testing Best Practices
Apex Testing Best PracticesApex Testing Best Practices
Apex Testing Best Practices
 
salesforce triggers interview questions and answers
salesforce triggers interview questions and answerssalesforce triggers interview questions and answers
salesforce triggers interview questions and answers
 
Lwc presentation
Lwc presentationLwc presentation
Lwc presentation
 
Managing Your Batch and Scheduled Apex Processes with Relax
Managing Your Batch and Scheduled Apex Processes with RelaxManaging Your Batch and Scheduled Apex Processes with Relax
Managing Your Batch and Scheduled Apex Processes with Relax
 
Governor limits
Governor limitsGovernor limits
Governor limits
 
Best Practices for RESTful Web Services
Best Practices for RESTful Web ServicesBest Practices for RESTful Web Services
Best Practices for RESTful Web Services
 
Visualforce & Force.com Canvas: Unlock your Web App inside of Salesforce.com ...
Visualforce & Force.com Canvas: Unlock your Web App inside of Salesforce.com ...Visualforce & Force.com Canvas: Unlock your Web App inside of Salesforce.com ...
Visualforce & Force.com Canvas: Unlock your Web App inside of Salesforce.com ...
 
Why Flow with Salesforce Flow
Why Flow with Salesforce FlowWhy Flow with Salesforce Flow
Why Flow with Salesforce Flow
 
Two-Way Integration with Writable External Objects
Two-Way Integration with Writable External ObjectsTwo-Way Integration with Writable External Objects
Two-Way Integration with Writable External Objects
 
REST API Design & Development
REST API Design & DevelopmentREST API Design & Development
REST API Design & Development
 
Salesforce Integration Patterns
Salesforce Integration PatternsSalesforce Integration Patterns
Salesforce Integration Patterns
 
Apex Enterprise Patterns: Building Strong Foundations
Apex Enterprise Patterns: Building Strong FoundationsApex Enterprise Patterns: Building Strong Foundations
Apex Enterprise Patterns: Building Strong Foundations
 
Asynchronous Apex Salesforce World Tour Paris 2015
Asynchronous Apex Salesforce World Tour Paris 2015Asynchronous Apex Salesforce World Tour Paris 2015
Asynchronous Apex Salesforce World Tour Paris 2015
 
Advanced Apex Development - Asynchronous Processes
Advanced Apex Development - Asynchronous ProcessesAdvanced Apex Development - Asynchronous Processes
Advanced Apex Development - Asynchronous Processes
 
Salesforce Development Best Practices
Salesforce Development Best PracticesSalesforce Development Best Practices
Salesforce Development Best Practices
 
Salesforce integration best practices columbus meetup
Salesforce integration best practices   columbus meetupSalesforce integration best practices   columbus meetup
Salesforce integration best practices columbus meetup
 
Apex trigger framework Salesforce #ApexTrigger #Salesforce #SFDCPanther
Apex trigger framework Salesforce #ApexTrigger #Salesforce #SFDCPantherApex trigger framework Salesforce #ApexTrigger #Salesforce #SFDCPanther
Apex trigger framework Salesforce #ApexTrigger #Salesforce #SFDCPanther
 
Intro to Force.com Canvas: Running External Apps within the Salesforce UI Web...
Intro to Force.com Canvas: Running External Apps within the Salesforce UI Web...Intro to Force.com Canvas: Running External Apps within the Salesforce UI Web...
Intro to Force.com Canvas: Running External Apps within the Salesforce UI Web...
 

En vedette

Design Patterns for Asynchronous Apex
Design Patterns for Asynchronous ApexDesign Patterns for Asynchronous Apex
Design Patterns for Asynchronous ApexSalesforce Developers
 
Process builder vs Triggers
Process builder vs TriggersProcess builder vs Triggers
Process builder vs TriggersProQuest
 
Apex Flex Queue: Batch Apex Liberated
Apex Flex Queue: Batch Apex LiberatedApex Flex Queue: Batch Apex Liberated
Apex Flex Queue: Batch Apex LiberatedCarolEnLaNube
 
Salesforce Process builder Vs Workflows
Salesforce Process builder Vs WorkflowsSalesforce Process builder Vs Workflows
Salesforce Process builder Vs WorkflowsPrasanna Deshpande ☁
 
Salesforce Apex Ten Commandments
Salesforce Apex Ten CommandmentsSalesforce Apex Ten Commandments
Salesforce Apex Ten CommandmentsNetStronghold
 
Enterprise Integration - Solution Patterns From the Field
Enterprise Integration - Solution Patterns From the FieldEnterprise Integration - Solution Patterns From the Field
Enterprise Integration - Solution Patterns From the FieldSalesforce Developers
 
Using the Tooling API to Generate Apex SOAP Web Service Clients
Using the Tooling API to Generate Apex SOAP Web Service ClientsUsing the Tooling API to Generate Apex SOAP Web Service Clients
Using the Tooling API to Generate Apex SOAP Web Service ClientsDaniel Ballinger
 
Spring '16 release belgium salesforce user group samuel de rycke
Spring '16 release belgium salesforce user group samuel de ryckeSpring '16 release belgium salesforce user group samuel de rycke
Spring '16 release belgium salesforce user group samuel de ryckeSamuel De Rycke
 
Integrate with External Systems using Apex Callouts
Integrate with External Systems using Apex CalloutsIntegrate with External Systems using Apex Callouts
Integrate with External Systems using Apex CalloutsSalesforce Developers
 
Dive Deep into Apex: Advanced Apex!
Dive Deep into Apex: Advanced Apex! Dive Deep into Apex: Advanced Apex!
Dive Deep into Apex: Advanced Apex! Salesforce Developers
 
Salesforce1 API Overview
Salesforce1 API OverviewSalesforce1 API Overview
Salesforce1 API OverviewSamuel De Rycke
 
Webinar: Integrating Salesforce and Slack (05 12-16)
Webinar: Integrating Salesforce and Slack (05 12-16)Webinar: Integrating Salesforce and Slack (05 12-16)
Webinar: Integrating Salesforce and Slack (05 12-16)Salesforce Developers
 
The Importance of Integration to Salesforce Success
The Importance of Integration to Salesforce SuccessThe Importance of Integration to Salesforce Success
The Importance of Integration to Salesforce SuccessDarren Cunningham
 
Secure Salesforce: External App Integrations
Secure Salesforce: External App IntegrationsSecure Salesforce: External App Integrations
Secure Salesforce: External App IntegrationsSalesforce Developers
 
Salesforce Multitenant Architecture: How We Do the Magic We Do
Salesforce Multitenant Architecture: How We Do the Magic We DoSalesforce Multitenant Architecture: How We Do the Magic We Do
Salesforce Multitenant Architecture: How We Do the Magic We DoSalesforce Developers
 

En vedette (19)

Design Patterns for Asynchronous Apex
Design Patterns for Asynchronous ApexDesign Patterns for Asynchronous Apex
Design Patterns for Asynchronous Apex
 
Process builder vs Triggers
Process builder vs TriggersProcess builder vs Triggers
Process builder vs Triggers
 
Apex Flex Queue: Batch Apex Liberated
Apex Flex Queue: Batch Apex LiberatedApex Flex Queue: Batch Apex Liberated
Apex Flex Queue: Batch Apex Liberated
 
Salesforce Process builder Vs Workflows
Salesforce Process builder Vs WorkflowsSalesforce Process builder Vs Workflows
Salesforce Process builder Vs Workflows
 
Salesforce Apex Ten Commandments
Salesforce Apex Ten CommandmentsSalesforce Apex Ten Commandments
Salesforce Apex Ten Commandments
 
Enterprise Integration - Solution Patterns From the Field
Enterprise Integration - Solution Patterns From the FieldEnterprise Integration - Solution Patterns From the Field
Enterprise Integration - Solution Patterns From the Field
 
Using the Tooling API to Generate Apex SOAP Web Service Clients
Using the Tooling API to Generate Apex SOAP Web Service ClientsUsing the Tooling API to Generate Apex SOAP Web Service Clients
Using the Tooling API to Generate Apex SOAP Web Service Clients
 
Apex Nirvana
Apex NirvanaApex Nirvana
Apex Nirvana
 
Spring '16 release belgium salesforce user group samuel de rycke
Spring '16 release belgium salesforce user group samuel de ryckeSpring '16 release belgium salesforce user group samuel de rycke
Spring '16 release belgium salesforce user group samuel de rycke
 
Salesforce APIs
Salesforce APIsSalesforce APIs
Salesforce APIs
 
Using Apex for REST Integration
Using Apex for REST IntegrationUsing Apex for REST Integration
Using Apex for REST Integration
 
Integrate with External Systems using Apex Callouts
Integrate with External Systems using Apex CalloutsIntegrate with External Systems using Apex Callouts
Integrate with External Systems using Apex Callouts
 
Dive Deep into Apex: Advanced Apex!
Dive Deep into Apex: Advanced Apex! Dive Deep into Apex: Advanced Apex!
Dive Deep into Apex: Advanced Apex!
 
Salesforce1 API Overview
Salesforce1 API OverviewSalesforce1 API Overview
Salesforce1 API Overview
 
Webinar: Integrating Salesforce and Slack (05 12-16)
Webinar: Integrating Salesforce and Slack (05 12-16)Webinar: Integrating Salesforce and Slack (05 12-16)
Webinar: Integrating Salesforce and Slack (05 12-16)
 
The Importance of Integration to Salesforce Success
The Importance of Integration to Salesforce SuccessThe Importance of Integration to Salesforce Success
The Importance of Integration to Salesforce Success
 
Secure Salesforce: External App Integrations
Secure Salesforce: External App IntegrationsSecure Salesforce: External App Integrations
Secure Salesforce: External App Integrations
 
Exploring the Salesforce REST API
Exploring the Salesforce REST APIExploring the Salesforce REST API
Exploring the Salesforce REST API
 
Salesforce Multitenant Architecture: How We Do the Magic We Do
Salesforce Multitenant Architecture: How We Do the Magic We DoSalesforce Multitenant Architecture: How We Do the Magic We Do
Salesforce Multitenant Architecture: How We Do the Magic We Do
 

Similaire à Salesforce asynchronous apex

Continuation_alan_20220503.pdf
Continuation_alan_20220503.pdfContinuation_alan_20220503.pdf
Continuation_alan_20220503.pdfShen yifeng
 
Deferred Processing in Ruby - Philly rb - August 2011
Deferred Processing in Ruby - Philly rb - August 2011Deferred Processing in Ruby - Philly rb - August 2011
Deferred Processing in Ruby - Philly rb - August 2011rob_dimarco
 
Salesforce Meetup 18 April 2015 - Apex Trigger & Scheduler Framworks
Salesforce Meetup 18 April 2015 - Apex Trigger & Scheduler FramworksSalesforce Meetup 18 April 2015 - Apex Trigger & Scheduler Framworks
Salesforce Meetup 18 April 2015 - Apex Trigger & Scheduler FramworksSumitkumar Shingavi
 
Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot NetNeeraj Kaushik
 
Building Complex Business Processes 3.7
Building Complex Business Processes 3.7Building Complex Business Processes 3.7
Building Complex Business Processes 3.7StephenKardian
 
Apex Liberation - the evolution of Flex Queue (DF15)
Apex Liberation - the evolution of Flex Queue (DF15)Apex Liberation - the evolution of Flex Queue (DF15)
Apex Liberation - the evolution of Flex Queue (DF15)Stephen Willcock
 
Task parallel library presentation
Task parallel library presentationTask parallel library presentation
Task parallel library presentationahmed sayed
 
End to-end async and await
End to-end async and awaitEnd to-end async and await
End to-end async and awaitvfabro
 
Junit in mule
Junit in muleJunit in mule
Junit in muleF K
 
Junit in mule demo
Junit in mule demo Junit in mule demo
Junit in mule demo javeed_mhd
 
Scaling asp.net websites to millions of users
Scaling asp.net websites to millions of usersScaling asp.net websites to millions of users
Scaling asp.net websites to millions of usersoazabir
 
Slideshare - Magento Imagine - Do You Queue
Slideshare - Magento Imagine - Do You QueueSlideshare - Magento Imagine - Do You Queue
Slideshare - Magento Imagine - Do You Queue10n Software, LLC
 

Similaire à Salesforce asynchronous apex (20)

Continuation_alan_20220503.pdf
Continuation_alan_20220503.pdfContinuation_alan_20220503.pdf
Continuation_alan_20220503.pdf
 
Deferred Processing in Ruby - Philly rb - August 2011
Deferred Processing in Ruby - Philly rb - August 2011Deferred Processing in Ruby - Philly rb - August 2011
Deferred Processing in Ruby - Philly rb - August 2011
 
Training – Going Async
Training – Going AsyncTraining – Going Async
Training – Going Async
 
Salesforce Meetup 18 April 2015 - Apex Trigger & Scheduler Framworks
Salesforce Meetup 18 April 2015 - Apex Trigger & Scheduler FramworksSalesforce Meetup 18 April 2015 - Apex Trigger & Scheduler Framworks
Salesforce Meetup 18 April 2015 - Apex Trigger & Scheduler Framworks
 
Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot Net
 
AtoM's Command Line Tasks - An Introduction
AtoM's Command Line Tasks - An IntroductionAtoM's Command Line Tasks - An Introduction
AtoM's Command Line Tasks - An Introduction
 
Building Complex Business Processes 3.7
Building Complex Business Processes 3.7Building Complex Business Processes 3.7
Building Complex Business Processes 3.7
 
Celery with python
Celery with pythonCelery with python
Celery with python
 
J unit
J unitJ unit
J unit
 
Apex Liberation - the evolution of Flex Queue (DF15)
Apex Liberation - the evolution of Flex Queue (DF15)Apex Liberation - the evolution of Flex Queue (DF15)
Apex Liberation - the evolution of Flex Queue (DF15)
 
Celery
CeleryCelery
Celery
 
Task parallel library presentation
Task parallel library presentationTask parallel library presentation
Task parallel library presentation
 
End to-end async and await
End to-end async and awaitEnd to-end async and await
End to-end async and await
 
Junit in mule
Junit in muleJunit in mule
Junit in mule
 
Junit in mule
Junit in muleJunit in mule
Junit in mule
 
Junit in mule demo
Junit in mule demo Junit in mule demo
Junit in mule demo
 
Junit in mule
Junit in muleJunit in mule
Junit in mule
 
Concurrency and parallel in .net
Concurrency and parallel in .netConcurrency and parallel in .net
Concurrency and parallel in .net
 
Scaling asp.net websites to millions of users
Scaling asp.net websites to millions of usersScaling asp.net websites to millions of users
Scaling asp.net websites to millions of users
 
Slideshare - Magento Imagine - Do You Queue
Slideshare - Magento Imagine - Do You QueueSlideshare - Magento Imagine - Do You Queue
Slideshare - Magento Imagine - Do You Queue
 

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