SlideShare a Scribd company logo
1 of 21
Asynchronous Apex
Begin Your Salesforce Coding Adventure
Created By: furuCRM Japan
Created Date: 2021/1/11
Agenda
• What is Async Proccessing?
• Understanding 4 type Async
• Sample code
• Q&A
What is Async Proccessing?
• Explain the difference between synchronous and asynchronous processing
• The key benefits of asynchronous processing include:
 User efficiency
 Scalability
 Higher Limits
What is Async Proccessing?
• Choose which kind of asynchronous Apex to use in various scenarios
Future Methods
• Future methods are typically used for:
 Async processing (simple and often)
 Long-running operations (Callouts to external web services)
 Separating mixed DML operations
• How can I define future method?
 with the future annotation
 must be static methods, and can only return a void type
 Specify (callout=true) to allow callouts
Methods
• You can invoke future methods the same way
you invoke any other method. However, a future
method can’t invoke another future method.
• Methods with the future annotation have the
following limits:
 Total number of SOQL queries issued: 200, Total
heap size: 12MB, Maximum CPU time on the
Salesforce servers:60,000 milliseconds
 Maximum number of methods with the future
annotation allowed per Apex invocation:
Synchronous Limit: 50, Asynchronous Limit: 0 in
batch and future contexts; 1 in queueable context
 The maximum number of future method invocations per
a 24-hour period is 250,000 or the number of user
licenses in your organization multiplied by 200,
whichever is greater.
 This limit is for your entire org and is shared with all
asynchronous Apex: Batch Apex, Queueable Apex,
scheduled Apex, and future methods.
 To check how many asynchronous Apex executions are
available, make a request to REST API limits resource:
Reference:
https://developer.salesforce.com/docs/atlas.en-
us.224.0.api_rest.meta/api_rest/dome_limits.htm
Future Methods
• Advantages:
 Asynchronous processing without a concurrent limit (queue)
 Easier and quicker to implement as opposed to Batch
• Disadvantages
 Parameters passed in can be only of Primitive type
 Can’t chain @future methods
 Difficult access to job ID
Queueable Apex
• Queueable Apex are typically used for:
 Chaining jobs: You can chain one job to another job by starting a second job from a running job. Chaining jobs
is useful if your process depends on another process to have run first
 You need @future method with support for non-primitive type. Your queueable class can contain member
variables of non-primitive data types, such as sObjects or custom Apex types. Those objects can be accessed
when the job executes
 Asynchronous monitoring
• How can I define Queueable Apex?
 Implement the Queueable interface
 Define execute() method
• How can I enqueue a job?
ID jobID = System.enqueueJob(SomeClass);
Queueable Apex Example
• The job is added to the queue and will be
processed when system resources become
available. You can monitor the status of your job
programmatically by querying AsyncApexJob or
through the user interface in Setup by entering
Apex Jobs in the Quick Find box, then selecting
Apex Jobs.
• Queueable Apex have the following limits:
 Total number of SOQL queries issued: 200, Total
heap size: 12MB, Maximum CPU time on the
Salesforce servers:60,000 milliseconds
 The maximum number of asynchronous Apex method
executions per a 24-hour period is 250,000 or the
number of user licenses in your organization multiplied
by 200, whichever is greater.
 You can add up to 50 jobs to the queue with
System.enqueueJob in a single
transaction(Synchronous Limit).
 In asynchronous transactions (for example, from a
batch Apex job), you can add only one job to the
queue with System.enqueueJob
Queueable Apex: chaining jobs
• When?
 To run a job after some other processing is done first by another job
• How?
 submit the second job from the execute() method of your queueable class
 You can add only one job from an executing job
 No limit is enforced on the depth of chained jobs. But For Developer Edition and Trial organizations: 5 jobs
including the initial parent queueable job
Batch Apex
• When should I use it?
 Complex long running processes (thousands of records). For
example: Data cleansing or archiving of records. Batch Apex
operates over small batches of records, covering your entire
record set and breaking the processing down to manageable
chunks
 Asynchronous processing
 Scheduled jobs
Batch Apex: How to define a Batch?
• Implement Database.Batchable Interface
• Three methods that must be implemented:
 start()
 Database.QueryLocator: 50M records, using
a simple query (SELECT) to generate the
scope of objects in the batch job
 Iterable: 50, 000 records, to create a
complex scope for the batch job
 execute()
 To do the required processing for each
chunk or batch of data passed to the method
 Default batch size: 200 record
 Batches of records are not guaranteed to
execute in the order they are received from
the start method.
 finish()
 Is called after all batches are processed
 To send confirmation emails or execute post-
processing operations
 Chaining Batch Jobs: Starting with API
version 26.0. By calling
Database.executeBatch or
System.scheduleBatch. The new batch job
will start after the current batch job finishes.
• Each execution of a batch Apex job is considered a discrete
transaction
• 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.
• To invoke a batch class, simply instantiate it and then call
Database.executeBatch with the instance:
• To specify the number of records that should be passed into the
execute method for each batch.
Batch Apex: Using State
• 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 is considered five transactions of 200 records each.
• Static member variables don’t retain their values and are reset back to original value
between transactions
• If you specify Database.Stateful in the class definition, you can maintain state across
these transactions. When using Database.Stateful, only instance member variables
retain their values between transactions.
• Maintaining state is useful for counting or summarizing records as they’re processed.
Batch Apex: Sample Code
Batch Apex: Governor Limits
 Up to 5 batch jobs can be queued or active concurrently.
 Up to 100 Holding batch jobs can be held in the Apex flex queue.
 In a running test, you can submit a maximum of 5 batch jobs.
 The maximum number of batch Apex method executions per 24-hour period is 250,000, or the number of user
licenses in your org multiplied by 200—whichever is greater. Method executions include executions of the start,
execute, and finish methods.
 A maximum of 50 million records can be returned in the Database.QueryLocator object.
 If the start method of the batch class returns a QueryLocator, the optional scope parameter of
Database.executeBatch can have a maximum value of 2,000. If set to a higher value, Salesforce chunks the
records returned by the QueryLocator into smaller batches of up to 2,000 records. If the start method of the
batch class returns an iterable, the scope parameter value has no upper limit. However, if you use a high
number, you can run into other limits.
 The start, execute, and finish methods can implement up to 100 callouts each.
 Only one batch Apex job's start method can run at a time in an org. Batch jobs that haven’t started yet remain
in the queue until they're started. Note that this limit doesn’t cause any batch job to fail and execute methods of
batch Apex jobs still run in parallel if more than one job is running.
Apex Scheduler
• When should I use it?
 Delay execution, run Apex classes at a specified time
 Daily or weekly maintenance tasks using Batch Apex
Scheduled Apex Syntax
• implement the Schedulable interface for the class
• Execute() method must be implemented
• Use the System.Schedule method to execute
 three arguments: a name for the job, an expression used to represent the time and date the job is scheduled to run, and
the name of the class.
• Using the System.scheduleBatch Method for Batch Jobs
 doesn’t require the implementation of the Schedulable interface
 This method is available only for batch classes
Scheduled Apex Syntax
Limits
 Maximum 100 jobs can be scheduled concurrently
 The maximum number of scheduled Apex executions per a 24-hour period is 250,000 or the number of user
licenses in your organization multiplied by 200, whichever is greater. This limit is for your entire org and is
shared with all asynchronous Apex: Batch Apex, Queueable Apex, scheduled Apex, and future methods.
 Synchronous Web service callouts are not supported from scheduled Apex. To be able to make callouts, make
an asynchronous callout by placing the callout in a method annotated with @future(callout=true) and call this
method from scheduled Apex. However, if your scheduled Apex executes a batch job, callouts are supported
from the batch class
Scheduled Apex : Sample
Code
Thanks for watching

More Related Content

What's hot

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
 
Integrating with salesforce
Integrating with salesforceIntegrating with salesforce
Integrating with salesforceMark Adcock
 
Apex Trigger in Salesforce
Apex Trigger in SalesforceApex Trigger in Salesforce
Apex Trigger in SalesforceCloud Analogy
 
salesforce triggers interview questions and answers
salesforce triggers interview questions and answerssalesforce triggers interview questions and answers
salesforce triggers interview questions and answersbhanuadmob
 
Episode 19 - Asynchronous Apex - Batch apex & schedulers
Episode 19 - Asynchronous Apex - Batch apex & schedulersEpisode 19 - Asynchronous Apex - Batch apex & schedulers
Episode 19 - Asynchronous Apex - Batch apex & schedulersJitendra Zaa
 
Salesforce Development Best Practices
Salesforce Development Best PracticesSalesforce Development Best Practices
Salesforce Development Best PracticesVivek Chawla
 
Advanced Apex Development - Asynchronous Processes
Advanced Apex Development - Asynchronous ProcessesAdvanced Apex Development - Asynchronous Processes
Advanced Apex Development - Asynchronous ProcessesSalesforce Developers
 
Introduction to apex code
Introduction to apex codeIntroduction to apex code
Introduction to apex codeEdwinOstos
 
Salesforce integration best practices columbus meetup
Salesforce integration best practices   columbus meetupSalesforce integration best practices   columbus meetup
Salesforce integration best practices columbus meetupMuleSoft Meetup
 
Introduction To Salesforce Content Management System (CMS)
Introduction To Salesforce Content Management System (CMS)Introduction To Salesforce Content Management System (CMS)
Introduction To Salesforce Content Management System (CMS)Cloud Analogy
 
Salesforce Integration Pattern Overview
Salesforce Integration Pattern OverviewSalesforce Integration Pattern Overview
Salesforce Integration Pattern OverviewDhanik Sahni
 
Approval Process in Salesforce
Approval Process in SalesforceApproval Process in Salesforce
Approval Process in SalesforceCloudTech 
 
Salesforce DUG - Queueable Apex
Salesforce DUG - Queueable ApexSalesforce DUG - Queueable Apex
Salesforce DUG - Queueable ApexAkshay Varu
 
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
 

What's hot (20)

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
 
Introduction to Apex for Developers
Introduction to Apex for DevelopersIntroduction to Apex for Developers
Introduction to Apex for Developers
 
Integrating with salesforce
Integrating with salesforceIntegrating with salesforce
Integrating with salesforce
 
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
 
Apex Trigger in Salesforce
Apex Trigger in SalesforceApex Trigger in Salesforce
Apex Trigger in Salesforce
 
salesforce triggers interview questions and answers
salesforce triggers interview questions and answerssalesforce triggers interview questions and answers
salesforce triggers interview questions and answers
 
Apex Design Patterns
Apex Design PatternsApex Design Patterns
Apex Design Patterns
 
Introduction to Apex Triggers
Introduction to Apex TriggersIntroduction to Apex Triggers
Introduction to Apex Triggers
 
Episode 19 - Asynchronous Apex - Batch apex & schedulers
Episode 19 - Asynchronous Apex - Batch apex & schedulersEpisode 19 - Asynchronous Apex - Batch apex & schedulers
Episode 19 - Asynchronous Apex - Batch apex & schedulers
 
SOQL & SOSL for Admins
SOQL & SOSL for AdminsSOQL & SOSL for Admins
SOQL & SOSL for Admins
 
Salesforce Development Best Practices
Salesforce Development Best PracticesSalesforce Development Best Practices
Salesforce Development Best Practices
 
Advanced Apex Development - Asynchronous Processes
Advanced Apex Development - Asynchronous ProcessesAdvanced Apex Development - Asynchronous Processes
Advanced Apex Development - Asynchronous Processes
 
Introduction to apex code
Introduction to apex codeIntroduction to apex code
Introduction to apex code
 
Salesforce integration best practices columbus meetup
Salesforce integration best practices   columbus meetupSalesforce integration best practices   columbus meetup
Salesforce integration best practices columbus meetup
 
Introduction To Salesforce Content Management System (CMS)
Introduction To Salesforce Content Management System (CMS)Introduction To Salesforce Content Management System (CMS)
Introduction To Salesforce Content Management System (CMS)
 
Salesforce Integration Pattern Overview
Salesforce Integration Pattern OverviewSalesforce Integration Pattern Overview
Salesforce Integration Pattern Overview
 
Approval Process in Salesforce
Approval Process in SalesforceApproval Process in Salesforce
Approval Process in Salesforce
 
Salesforce DUG - Queueable Apex
Salesforce DUG - Queueable ApexSalesforce DUG - Queueable Apex
Salesforce DUG - Queueable Apex
 
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
 

Similar to Asynchronous apex

Salesforce Apex Hours :- Hyper batch
Salesforce Apex Hours :- Hyper batchSalesforce Apex Hours :- Hyper batch
Salesforce Apex Hours :- Hyper batchAmit Chaudhary
 
Actionable Insights with Apache Apex at Apache Big Data 2017 by Devendra Tagare
Actionable Insights with Apache Apex at Apache Big Data 2017 by Devendra TagareActionable Insights with Apache Apex at Apache Big Data 2017 by Devendra Tagare
Actionable Insights with Apache Apex at Apache Big Data 2017 by Devendra TagareApache Apex
 
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
 
Hyperbatch (LoteRapido) - Punta Dreamin' 2017
Hyperbatch (LoteRapido) - Punta Dreamin' 2017Hyperbatch (LoteRapido) - Punta Dreamin' 2017
Hyperbatch (LoteRapido) - Punta Dreamin' 2017Daniel Peter
 
Continuation_alan_20220503.pdf
Continuation_alan_20220503.pdfContinuation_alan_20220503.pdf
Continuation_alan_20220503.pdfShen yifeng
 
Rate limits and Performance
Rate limits and PerformanceRate limits and Performance
Rate limits and Performancesupergigas
 
Parallel Computing - Lec 6
Parallel Computing - Lec 6Parallel Computing - Lec 6
Parallel Computing - Lec 6Shah Zaib
 
Square Peg Round Hole: Serverless Solutions For Non-Serverless Problems
Square Peg Round Hole: Serverless Solutions For Non-Serverless ProblemsSquare Peg Round Hole: Serverless Solutions For Non-Serverless Problems
Square Peg Round Hole: Serverless Solutions For Non-Serverless ProblemsChase Douglas
 
Apache Big Data 2016: Next Gen Big Data Analytics with Apache Apex
Apache Big Data 2016: Next Gen Big Data Analytics with Apache ApexApache Big Data 2016: Next Gen Big Data Analytics with Apache Apex
Apache Big Data 2016: Next Gen Big Data Analytics with Apache ApexApache Apex
 
Performance of processor.ppt
Performance of processor.pptPerformance of processor.ppt
Performance of processor.pptnivedita murugan
 
End to-end async and await
End to-end async and awaitEnd to-end async and await
End to-end async and awaitvfabro
 
3.2 Streaming and Messaging
3.2 Streaming and Messaging3.2 Streaming and Messaging
3.2 Streaming and Messaging振东 刘
 
Performance eng prakash.sahu
Performance eng prakash.sahuPerformance eng prakash.sahu
Performance eng prakash.sahuDr. Prakash Sahu
 
Seven deadly sins of ElasticSearch Benchmarking
Seven deadly sins of ElasticSearch BenchmarkingSeven deadly sins of ElasticSearch Benchmarking
Seven deadly sins of ElasticSearch BenchmarkingFan Robbin
 
Secrets of highly_avail_oltp_archs
Secrets of highly_avail_oltp_archsSecrets of highly_avail_oltp_archs
Secrets of highly_avail_oltp_archsTarik Essawi
 
Intro to Apache Apex - Next Gen Platform for Ingest and Transform
Intro to Apache Apex - Next Gen Platform for Ingest and TransformIntro to Apache Apex - Next Gen Platform for Ingest and Transform
Intro to Apache Apex - Next Gen Platform for Ingest and TransformApache Apex
 
WinOps Conf 2016 - Michael Greene - Release Pipelines
WinOps Conf 2016 - Michael Greene - Release PipelinesWinOps Conf 2016 - Michael Greene - Release Pipelines
WinOps Conf 2016 - Michael Greene - Release PipelinesWinOps Conf
 

Similar to Asynchronous apex (20)

Salesforce Apex Hours :- Hyper batch
Salesforce Apex Hours :- Hyper batchSalesforce Apex Hours :- Hyper batch
Salesforce Apex Hours :- Hyper batch
 
Actionable Insights with Apache Apex at Apache Big Data 2017 by Devendra Tagare
Actionable Insights with Apache Apex at Apache Big Data 2017 by Devendra TagareActionable Insights with Apache Apex at Apache Big Data 2017 by Devendra Tagare
Actionable Insights with Apache Apex at Apache Big Data 2017 by Devendra Tagare
 
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
 
Hyperbatch (LoteRapido) - Punta Dreamin' 2017
Hyperbatch (LoteRapido) - Punta Dreamin' 2017Hyperbatch (LoteRapido) - Punta Dreamin' 2017
Hyperbatch (LoteRapido) - Punta Dreamin' 2017
 
Continuation_alan_20220503.pdf
Continuation_alan_20220503.pdfContinuation_alan_20220503.pdf
Continuation_alan_20220503.pdf
 
Rate limits and Performance
Rate limits and PerformanceRate limits and Performance
Rate limits and Performance
 
Parallel Computing - Lec 6
Parallel Computing - Lec 6Parallel Computing - Lec 6
Parallel Computing - Lec 6
 
Square Peg Round Hole: Serverless Solutions For Non-Serverless Problems
Square Peg Round Hole: Serverless Solutions For Non-Serverless ProblemsSquare Peg Round Hole: Serverless Solutions For Non-Serverless Problems
Square Peg Round Hole: Serverless Solutions For Non-Serverless Problems
 
Apache Big Data 2016: Next Gen Big Data Analytics with Apache Apex
Apache Big Data 2016: Next Gen Big Data Analytics with Apache ApexApache Big Data 2016: Next Gen Big Data Analytics with Apache Apex
Apache Big Data 2016: Next Gen Big Data Analytics with Apache Apex
 
Performance of processor.ppt
Performance of processor.pptPerformance of processor.ppt
Performance of processor.ppt
 
End to-end async and await
End to-end async and awaitEnd to-end async and await
End to-end async and await
 
3.2 Streaming and Messaging
3.2 Streaming and Messaging3.2 Streaming and Messaging
3.2 Streaming and Messaging
 
slides (PPT)
slides (PPT)slides (PPT)
slides (PPT)
 
Performance eng prakash.sahu
Performance eng prakash.sahuPerformance eng prakash.sahu
Performance eng prakash.sahu
 
Typesafe spark- Zalando meetup
Typesafe spark- Zalando meetupTypesafe spark- Zalando meetup
Typesafe spark- Zalando meetup
 
Seven deadly sins of ElasticSearch Benchmarking
Seven deadly sins of ElasticSearch BenchmarkingSeven deadly sins of ElasticSearch Benchmarking
Seven deadly sins of ElasticSearch Benchmarking
 
Secrets of highly_avail_oltp_archs
Secrets of highly_avail_oltp_archsSecrets of highly_avail_oltp_archs
Secrets of highly_avail_oltp_archs
 
Intro to Apache Apex - Next Gen Platform for Ingest and Transform
Intro to Apache Apex - Next Gen Platform for Ingest and TransformIntro to Apache Apex - Next Gen Platform for Ingest and Transform
Intro to Apache Apex - Next Gen Platform for Ingest and Transform
 
WinOps Conf 2016 - Michael Greene - Release Pipelines
WinOps Conf 2016 - Michael Greene - Release PipelinesWinOps Conf 2016 - Michael Greene - Release Pipelines
WinOps Conf 2016 - Michael Greene - Release Pipelines
 

More from furuCRM株式会社 CEO/Dreamforce Vietnam Founder

More from furuCRM株式会社 CEO/Dreamforce Vietnam Founder (20)

GithubAction+DevOpsCenter.pptx
GithubAction+DevOpsCenter.pptxGithubAction+DevOpsCenter.pptx
GithubAction+DevOpsCenter.pptx
 
BackupMetadataByGitAction.pptx
BackupMetadataByGitAction.pptxBackupMetadataByGitAction.pptx
BackupMetadataByGitAction.pptx
 
Salesforce Flow_InternalTraining.pptx
Salesforce Flow_InternalTraining.pptxSalesforce Flow_InternalTraining.pptx
Salesforce Flow_InternalTraining.pptx
 
FlowErrorHandling.pptx
FlowErrorHandling.pptxFlowErrorHandling.pptx
FlowErrorHandling.pptx
 
DevOpsCenter_BetaVersion.pptx
DevOpsCenter_BetaVersion.pptxDevOpsCenter_BetaVersion.pptx
DevOpsCenter_BetaVersion.pptx
 
Omni-Chanel_ForInternal.pptx
Omni-Chanel_ForInternal.pptxOmni-Chanel_ForInternal.pptx
Omni-Chanel_ForInternal.pptx
 
基本設計+詳細設計の書き方 社内勉強会0304
基本設計+詳細設計の書き方 社内勉強会0304基本設計+詳細設計の書き方 社内勉強会0304
基本設計+詳細設計の書き方 社内勉強会0304
 
SVF cloud for salesforce
SVF cloud for salesforceSVF cloud for salesforce
SVF cloud for salesforce
 
External services
External servicesExternal services
External services
 
Data spider servista for Beginner
Data spider servista for BeginnerData spider servista for Beginner
Data spider servista for Beginner
 
Record level-access in Salesforce
Record level-access in SalesforceRecord level-access in Salesforce
Record level-access in Salesforce
 
Salesforce CMS
Salesforce CMS Salesforce CMS
Salesforce CMS
 
Salesforce Scheduler
Salesforce SchedulerSalesforce Scheduler
Salesforce Scheduler
 
Pardot MA Fundamental
Pardot MA FundamentalPardot MA Fundamental
Pardot MA Fundamental
 
Field service lightning
Field service lightningField service lightning
Field service lightning
 
ETL And Salesforce Integration
ETL And Salesforce IntegrationETL And Salesforce Integration
ETL And Salesforce Integration
 
Sfdx jenkins
Sfdx jenkinsSfdx jenkins
Sfdx jenkins
 
Heroku platform introduction
Heroku platform introductionHeroku platform introduction
Heroku platform introduction
 
Unlocked package
Unlocked packageUnlocked package
Unlocked package
 
Sales cloud overview
Sales cloud overviewSales cloud overview
Sales cloud overview
 

Recently uploaded

Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 
JohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptxJohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptxJohnPollard37
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontologyjohnbeverley2021
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
Simplifying Mobile A11y Presentation.pptx
Simplifying Mobile A11y Presentation.pptxSimplifying Mobile A11y Presentation.pptx
Simplifying Mobile A11y Presentation.pptxMarkSteadman7
 
JavaScript Usage Statistics 2024 - The Ultimate Guide
JavaScript Usage Statistics 2024 - The Ultimate GuideJavaScript Usage Statistics 2024 - The Ultimate Guide
JavaScript Usage Statistics 2024 - The Ultimate GuidePixlogix Infotech
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
Stronger Together: Developing an Organizational Strategy for Accessible Desig...
Stronger Together: Developing an Organizational Strategy for Accessible Desig...Stronger Together: Developing an Organizational Strategy for Accessible Desig...
Stronger Together: Developing an Organizational Strategy for Accessible Desig...caitlingebhard1
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfOrbitshub
 
Design and Development of a Provenance Capture Platform for Data Science
Design and Development of a Provenance Capture Platform for Data ScienceDesign and Development of a Provenance Capture Platform for Data Science
Design and Development of a Provenance Capture Platform for Data SciencePaolo Missier
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Zilliz
 
Modernizing Legacy Systems Using Ballerina
Modernizing Legacy Systems Using BallerinaModernizing Legacy Systems Using Ballerina
Modernizing Legacy Systems Using BallerinaWSO2
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxRemote DBA Services
 
TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....
TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....
TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....rightmanforbloodline
 

Recently uploaded (20)

Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
JohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptxJohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptx
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Simplifying Mobile A11y Presentation.pptx
Simplifying Mobile A11y Presentation.pptxSimplifying Mobile A11y Presentation.pptx
Simplifying Mobile A11y Presentation.pptx
 
JavaScript Usage Statistics 2024 - The Ultimate Guide
JavaScript Usage Statistics 2024 - The Ultimate GuideJavaScript Usage Statistics 2024 - The Ultimate Guide
JavaScript Usage Statistics 2024 - The Ultimate Guide
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Stronger Together: Developing an Organizational Strategy for Accessible Desig...
Stronger Together: Developing an Organizational Strategy for Accessible Desig...Stronger Together: Developing an Organizational Strategy for Accessible Desig...
Stronger Together: Developing an Organizational Strategy for Accessible Desig...
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Design and Development of a Provenance Capture Platform for Data Science
Design and Development of a Provenance Capture Platform for Data ScienceDesign and Development of a Provenance Capture Platform for Data Science
Design and Development of a Provenance Capture Platform for Data Science
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Modernizing Legacy Systems Using Ballerina
Modernizing Legacy Systems Using BallerinaModernizing Legacy Systems Using Ballerina
Modernizing Legacy Systems Using Ballerina
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....
TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....
TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....
 

Asynchronous apex

  • 1. Asynchronous Apex Begin Your Salesforce Coding Adventure Created By: furuCRM Japan Created Date: 2021/1/11
  • 2. Agenda • What is Async Proccessing? • Understanding 4 type Async • Sample code • Q&A
  • 3. What is Async Proccessing? • Explain the difference between synchronous and asynchronous processing • The key benefits of asynchronous processing include:  User efficiency  Scalability  Higher Limits
  • 4. What is Async Proccessing? • Choose which kind of asynchronous Apex to use in various scenarios
  • 5. Future Methods • Future methods are typically used for:  Async processing (simple and often)  Long-running operations (Callouts to external web services)  Separating mixed DML operations • How can I define future method?  with the future annotation  must be static methods, and can only return a void type  Specify (callout=true) to allow callouts
  • 6. Methods • You can invoke future methods the same way you invoke any other method. However, a future method can’t invoke another future method. • Methods with the future annotation have the following limits:  Total number of SOQL queries issued: 200, Total heap size: 12MB, Maximum CPU time on the Salesforce servers:60,000 milliseconds  Maximum number of methods with the future annotation allowed per Apex invocation: Synchronous Limit: 50, Asynchronous Limit: 0 in batch and future contexts; 1 in queueable context  The maximum number of future method invocations per a 24-hour period is 250,000 or the number of user licenses in your organization multiplied by 200, whichever is greater.  This limit is for your entire org and is shared with all asynchronous Apex: Batch Apex, Queueable Apex, scheduled Apex, and future methods.  To check how many asynchronous Apex executions are available, make a request to REST API limits resource: Reference: https://developer.salesforce.com/docs/atlas.en- us.224.0.api_rest.meta/api_rest/dome_limits.htm
  • 7. Future Methods • Advantages:  Asynchronous processing without a concurrent limit (queue)  Easier and quicker to implement as opposed to Batch • Disadvantages  Parameters passed in can be only of Primitive type  Can’t chain @future methods  Difficult access to job ID
  • 8. Queueable Apex • Queueable Apex are typically used for:  Chaining jobs: You can chain one job to another job by starting a second job from a running job. Chaining jobs is useful if your process depends on another process to have run first  You need @future method with support for non-primitive type. Your queueable class can contain member variables of non-primitive data types, such as sObjects or custom Apex types. Those objects can be accessed when the job executes  Asynchronous monitoring • How can I define Queueable Apex?  Implement the Queueable interface  Define execute() method • How can I enqueue a job? ID jobID = System.enqueueJob(SomeClass);
  • 9. Queueable Apex Example • The job is added to the queue and will be processed when system resources become available. You can monitor the status of your job programmatically by querying AsyncApexJob or through the user interface in Setup by entering Apex Jobs in the Quick Find box, then selecting Apex Jobs. • Queueable Apex have the following limits:  Total number of SOQL queries issued: 200, Total heap size: 12MB, Maximum CPU time on the Salesforce servers:60,000 milliseconds  The maximum number of asynchronous Apex method executions per a 24-hour period is 250,000 or the number of user licenses in your organization multiplied by 200, whichever is greater.  You can add up to 50 jobs to the queue with System.enqueueJob in a single transaction(Synchronous Limit).  In asynchronous transactions (for example, from a batch Apex job), you can add only one job to the queue with System.enqueueJob
  • 10. Queueable Apex: chaining jobs • When?  To run a job after some other processing is done first by another job • How?  submit the second job from the execute() method of your queueable class  You can add only one job from an executing job  No limit is enforced on the depth of chained jobs. But For Developer Edition and Trial organizations: 5 jobs including the initial parent queueable job
  • 11. Batch Apex • When should I use it?  Complex long running processes (thousands of records). For example: Data cleansing or archiving of records. Batch Apex operates over small batches of records, covering your entire record set and breaking the processing down to manageable chunks  Asynchronous processing  Scheduled jobs
  • 12. Batch Apex: How to define a Batch? • Implement Database.Batchable Interface • Three methods that must be implemented:  start()  Database.QueryLocator: 50M records, using a simple query (SELECT) to generate the scope of objects in the batch job  Iterable: 50, 000 records, to create a complex scope for the batch job  execute()  To do the required processing for each chunk or batch of data passed to the method  Default batch size: 200 record  Batches of records are not guaranteed to execute in the order they are received from the start method.  finish()  Is called after all batches are processed  To send confirmation emails or execute post- processing operations  Chaining Batch Jobs: Starting with API version 26.0. By calling Database.executeBatch or System.scheduleBatch. The new batch job will start after the current batch job finishes. • Each execution of a batch Apex job is considered a discrete transaction • 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. • To invoke a batch class, simply instantiate it and then call Database.executeBatch with the instance: • To specify the number of records that should be passed into the execute method for each batch.
  • 13. Batch Apex: Using State • 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 is considered five transactions of 200 records each. • Static member variables don’t retain their values and are reset back to original value between transactions • If you specify Database.Stateful in the class definition, you can maintain state across these transactions. When using Database.Stateful, only instance member variables retain their values between transactions. • Maintaining state is useful for counting or summarizing records as they’re processed.
  • 15. Batch Apex: Governor Limits  Up to 5 batch jobs can be queued or active concurrently.  Up to 100 Holding batch jobs can be held in the Apex flex queue.  In a running test, you can submit a maximum of 5 batch jobs.  The maximum number of batch Apex method executions per 24-hour period is 250,000, or the number of user licenses in your org multiplied by 200—whichever is greater. Method executions include executions of the start, execute, and finish methods.  A maximum of 50 million records can be returned in the Database.QueryLocator object.  If the start method of the batch class returns a QueryLocator, the optional scope parameter of Database.executeBatch can have a maximum value of 2,000. If set to a higher value, Salesforce chunks the records returned by the QueryLocator into smaller batches of up to 2,000 records. If the start method of the batch class returns an iterable, the scope parameter value has no upper limit. However, if you use a high number, you can run into other limits.  The start, execute, and finish methods can implement up to 100 callouts each.  Only one batch Apex job's start method can run at a time in an org. Batch jobs that haven’t started yet remain in the queue until they're started. Note that this limit doesn’t cause any batch job to fail and execute methods of batch Apex jobs still run in parallel if more than one job is running.
  • 16. Apex Scheduler • When should I use it?  Delay execution, run Apex classes at a specified time  Daily or weekly maintenance tasks using Batch Apex
  • 17. Scheduled Apex Syntax • implement the Schedulable interface for the class • Execute() method must be implemented • Use the System.Schedule method to execute  three arguments: a name for the job, an expression used to represent the time and date the job is scheduled to run, and the name of the class. • Using the System.scheduleBatch Method for Batch Jobs  doesn’t require the implementation of the Schedulable interface  This method is available only for batch classes
  • 19. Limits  Maximum 100 jobs can be scheduled concurrently  The maximum number of scheduled Apex executions per a 24-hour period is 250,000 or the number of user licenses in your organization multiplied by 200, whichever is greater. This limit is for your entire org and is shared with all asynchronous Apex: Batch Apex, Queueable Apex, scheduled Apex, and future methods.  Synchronous Web service callouts are not supported from scheduled Apex. To be able to make callouts, make an asynchronous callout by placing the callout in a method annotated with @future(callout=true) and call this method from scheduled Apex. However, if your scheduled Apex executes a batch job, callouts are supported from the batch class
  • 20. Scheduled Apex : Sample Code

Editor's Notes

  1. ・Tóm lại, Async Apex được sử dụng để chạy các process trong một luồng riêng biệt, vào thời điểm sau đó later time ở tương lai ・ Là một process hoặc function thực thi 1 công việc in the background mà không cần User phải đợi Công việc đó nó kết thúc ・ 1 ví dụ khác là trên amazon khi bạn thực hiện mua hàng xong => amazon sẽ gửi email thông báo về tiến trình mua hàng, trạng thái đơn hàng, delivery… ・ở SF thì chúng ta cũng có thể làm như vậy với 1 trong 4 type trên hoặc other ====================================== ・ User efficiency: Những tính toán, công việc mặc dù chưa hoàn thành nhưng cũng không gây ảnh hưởng tới những gì user đang làm, hoặc sắp sửa làm -> chúng ta nên chọn xử lý bất đồng bộ, quá trình xử lý thực hiện in the background => user có thể tiếp tục công việc của họ, sau đó họ có thể xem những kết quả nếu muốn ・ Scalability: bằng cách cho phép thực thi khi resource sẵn sàng, đang free ở 1 thời điểm nào đó trong tương lai -> do đó nó có thể được quản lý và mở rộng(scaled) 1 cách nhanh chóng, => điều này cho phép xử lý được nhiều công việc hơn bằng cách thực hiện song song ・Higher Limits: =>
  2. Chúng ta sẽ đi đến chi tiết sau đây…
  3. Batch Apex hoạt động trên small batches của record, chia nhỏ quá trình xử lý thành các phần có thể quản lý được
  4. 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. To invoke a batch class, simply instantiate it and then call Database.executeBatch with the instance:
  5. After you implement a class with the Schedulable interface, use the System.Schedule method to execute it. The scheduler runs as system—all classes are executed, whether or not the user has permission to execute the class. doesn’t require the implementation of the Schedulable interface