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
・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: =>
Chúng ta sẽ đi đến chi tiết sau đây…
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
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:
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