0% found this document useful (0 votes)
61 views18 pages

SFDC Training - Day28

Uploaded by

vijay08arora
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
61 views18 pages

SFDC Training - Day28

Uploaded by

vijay08arora
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

Asynchronous Process

In technology terminology, Asynchronous operation means that a process operating


independently of other processes

Asynchronous vs Synchronous

Asynchronous
● Actions that will not block the transaction or Process
● Duration is not priority
● Higher Governor limits

Synchronous
● Quick and Immediate actions
● Transactions are immediate and serial
● Normal Governor Limits

CHECK OUT THE LIMITS:


https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_gov_lim
its.htm

Asynchronous Process on Salesforce Platform


● Ensure fairness of processing – Make sure every customer gets a fair chance at
processing resources.
● Ensure transactional capabilities – Ensure equipment or software failures allow
continued processing at reduced capacity and requests are persisted until
completion.
Queue based framework
● Enqueue – The request gets put into the queue. This could be an Apex batch
request, @future Apex request or one of many others. The Salesforce application
will enqueue requests along with the appropriate data to process that request.
● Persistence – The enqueued request gets persisted. Requests are stored in
persistent storage for failure recovery and to provide transactional capabilities.
● Dequeue – The enqueued request is removed from the the queue and processed.
Transaction management occurs in this step to assure messages are not lost if there
is a processing failure.
Why to use Async process Scenarios
● Integrations to External Applications
● Long running processes
● Mixed DML Operations
● Large volume of data loads & transactions

Using @future annotation


● A “set it and forget it” method
● Call it and the async job is launched
● No ability to monitor the job
● Cannot chain @future calls
● A public static method, decorated with @future
● Arguments: Primitives (Integer, String, etc.)
● Collections of primitives (List, Map, Set)
● NOT SObjects or Apex objects
● You can use JSON.serialize() and pass in a String
● Returns void

Queueable Class
● A class and method that can be added to the queue to be executed
● It’s monitorable and abortable
● It’s chainable
● A public class that implements the Queueable interface
● Includes an execute method that accepts only a QueueableContext parameter
● The execute method can access instance properties for the class
● Returns void
● Launch by calling System.enqueueJob(cls) with an instance of the class.
● Returns an AsyncApexJob Id

Using Batch Class


● A technique designed specifically for:
● Processing large numbers of records
● Doing more work than can be done in a single transaction
● It’s monitorable and abortable
● A global class that implements the Database.Batchable interface
● Includes:
○Start method – identifies the scope (list of data to be processed)

○Execute method – processes a subset of the scoped records

○Finish method – does any post-job wrap-up

Additional interfaces:

Database.Stateful

Database.AllowsCallouts
● Launch by calling Database.executeBatch(cls) with an instance of the class and an
optional scope size
● Default scope size is 200
● Max scope size is 2,000
● Returns an AsyncApexJobId

Schedulable Class
● A global class that implements the Schedulable interface
● Includes an execute method
● Schedule by calling
○ System.Schedule(‘job name’, cron expression, cls)
● Cron expression can be complex
● Returns a CronTrigger Id
● Can also schedule via the Salesforce UI
● seconds minutes hours day_of_month month day_of_week optional_year
Run at 30 minutes past midnight on Jan 1 every year
● GeocodingSchedulable cls = new GeocodingSchedulable();

System.Schedule(‘Geocode on Jan 1’, ‘0 30 0 1 1 ? *’, cls);

Run every hour


● System.Schedule(‘Geocode hourly’, ‘0 0 * * * ? *’, cls);

This table lists the asynchronous Apex features and when to use each.

Asynchronous When to Use


Apex Feature

Queueable Apex ● To start a long-running operation and get an ID for it


● To pass complex types to a job
● To chain jobs

Scheduled Apex ● To schedule an Apex class to run on a specific schedule

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

Future Methods
● Methods are annotated with @future annotation.
● Future methods should be static and can only return void type.
● It supports parameters, but parameters should be primitive data types, arrays of
primitive data types, or collection. sObjects or objects cannot be used as
parameters to future methods.
● These methods run in their own thread and will only start when the resources are
available.
● They are used for long running operations and prevent any delay in apex
transaction.
● They can be used for callouts to external web services and also separating DML
operations to prevent Mixed DML error.
● Future methods should not be used for processing large amounts of data. In
that case, Batch Apex should be used.
● To test future methods, enclose test code between startTest and stopTest test
methods.
● Future methods not necessarity execute in the same order as they are called.
● Future methods cannot be used inside Visualforce controllers getter, setter,
constructor methods.

Queueable Apex
● Apex code must implement Queueable interace.
● By implementing Queueable interface, Apex class can be added to the job queue
and it will run when the system resources are available.
● The difference between Queueable Apex and Future methods is –
○ Queueable Apex supports job-chaining
○ It supports non primitive data types likes sObjects or custom objects.
● System.enqueueJob method is used to submit the job. After submission, ID of
AsyncApexJob record is returned.
● Using SOQL, status of the queued job can be monitored programmatically by
querying AsyncApexJob table. The same is also possible from “Apex Jobs”in
setup.
● Chaining is supported here, thus allowing a job to be started from another
running job.
● The execution of a queued job counts once against the shared limit for
Asynchronous Apex method executions.
● Maximum 50 jobs can be added to the queue in a single transaction.
● Only one child job can exist for each parent job.
● There is no limit on the dept of the chained jobs.
Batch Apex
● Apex class must implement Database.Batchable interface, which will allow
them to write code against start, execute and finish methods.
● A batch class can be invoked by calling Database.executeBatch. It needs the
instance of the class and batch size.
● Using SOQL, status of the batch job can be monitored programmatically by
querying AsyncApexJob table. The same is also possible from “Apex Jobs”in
setup.
● It is used to process millions of records asynchronously.
● Apex jobs always get executed in a separate transaction.
● Every batch apex transactions has their own governor limit(new limit always).
Thus if one batch fails, it will not impact other batches.
● Start Method:
○ It is used to collect records or objects which will be passed to the method
“execute”.
○ It returns either a Database.QueryLocator object or an Iterable.
● Execute Method:
○ This method is responsible for doing the actual processing work.
○ Default batch size is 200.
○ Parameter it needs – a reference to Database.BatchableContext object and a
list of sObjects.
● Finish Method:
○ This method is used to do post-processing operations likes sending email
etc.

Scheduled Apex
● Apex class must implement Schedulable interface. By implementing this
interface, an apex class can be scheduled at specific time/day in the Apex
Scheduler.
● System.Schedule method is used to schedule an instance of the class.
● It should implement the execute method(this is the only method). Parameter –
SchedulableContext object.
● Once a class is scheduled, as CronTrigger object record is created. The
getTriggerId method can be used to return the ID of CronTrigger record.
● If the class is getting scheduled from Trigger, Governor limit should be checked.
● Additional processing should be done in a separate class outside of execute
method.
● Maximum 100 scheduled Apex jobs at one time is possible.
● Synchronous Web service callouts are not supported from scheduled apex. To do
that, make an asynchronous callout in a method annotated with
@future(callout=true) and then call it from scheduled apex. Note – If scheduled
apex exceutes batch job, then callouts are possible as they are supported from
batch class.

Reference:

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_async_o
verview.htm

Batch Apex Syntax


To write a Batch Apex class, your class must implement the Database.Batchable interface
and include the following three methods:

start

Start method is automatically called at the beginning of the apex job. This method will
collect record or objects on which the operation should be performed. These records are
divided into subtasks and pass those to execute method.

Used to collect the records or objects to be passed to the interface method execute for
processing. This method is called once at the beginning of a Batch Apex job and returns
either a Database.QueryLocator object or an Iterable that contains the records or objects
passed to the job.
Most of the time a QueryLocator does the trick with a simple SOQL query to generate the
scope of objects in the batch job. But if you need to do something crazy like loop through
the results of an API call or pre-process records before being passed to the execute
method, you might want to check out the Custom Iterators link in the Resources section.

With the QueryLocator object, the governor limit for the total number of records retrieved
by SOQL queries is bypassed and you can query up to 50 million records. However, with
an Iterable, the governor limit for the total number of records retrieved by SOQL queries
is still enforced.

execute

Execute Method performs an operation which we want to perform on the records fetched
from start method.

Performs the actual processing for each chunk or “batch” of data passed to the method.
The default batch size is 200 records. Batches of records are not guaranteed to execute in
the order they are received from the start method.

This method takes the following:

● A reference to the Database.BatchableContext object.


● A list of sObjects, such as List<sObject>, or a list of parameterized types. If you
are using a Database.QueryLocator, use the returned list.

finish

Finish method executes after all batches are processed. Use this method to send
confirmation email notifications
Used to execute post-processing operations (for example, sending an email) and is called
once after all batches are processed.

Here’s what the skeleton of a Batch Apex class looks like:

1
2 global class MyBatchClass implements Database.Batchable<sObject> {
3
global (Database.QueryLocator | Iterable<sObject>)
4
start(Database.BatchableContext bc) {
5
6 // collect the batches of records or objects to be passed to execute
7
8 }
9
global void execute(Database.BatchableContext bc, List<P> records){
10
11 // process each batch of records

global void finish(Database.BatchableContext bc){

// execute any post-processing operations

Key points about batch Apex


● To use batch Apex, write an Apex class that implements Database.Batchable
interface and make your class global
● Implement the following 3 methods
■ start()
■ execute()
■ finish()
● The default batch size is 200
Monitoring Batch Apex
To monitor or stop the execution of the batch Apex job, from Setup, enter Apex Jobs in
the Quick Find box, then select Apex Jobs.

Batch class in salesforce


Here is example of Batch class in salesforce

1
2 global class BatchApexExample implements Database.Batchable<sObject> {
3
global Database.QueryLocator start(Database.BatchableContext BC) {
4
5 // collect the batches of records or objects to be passed to execute
6
7
8
String query = 'SELECT Id, Name FROM Account';
9
10 return Database.getQueryLocator(query);
11
12 }
13
14
15 global void execute(Database.BatchableContext BC, List<Account> accList) {
16
17
18
19 // process each batch of records default size is 200
20 for(Account acc : accList) {
21
22 // Update the Account Name
23
24 acc.Name = acc.Name + 'sfdcpoint';
25
}
26
27
28
29 try {

// Update the Account Record

update accList;

} catch(Exception e) {

System.debug(e);

global void finish(Database.BatchableContext BC) {

// execute any post-processing operations like sending email

Invoking a Batch Class


To invoke a batch class, simply instantiate it and then call Database.executeBatch with
the instance:

1
2 MyBatchClass myBatchObject = new MyBatchClass();

Id batchId = Database.executeBatch(myBatchObject);
You can also optionally pass a second scope parameter to specify the number of records
that should be passed into the execute method for each batch. Pro tip: you might want to
limit this batch size if you are running into governor limits.
1
Id batchId = Database.executeBatch(myBatchObject, 100);
Each batch Apex invocation creates an AsyncApexJob record so that you can track the
job’s progress. You can view the progress via SOQL or manage your job in the Apex Job
Queue. We’ll talk about the Job Queue shortly.

1
AsyncApexJob job = [SELECT Id, Status, JobItemsProcessed, TotalJobItems,
NumberOfErrors FROM AsyncApexJob WHERE ID = :batchId ];

Scheduling Batch Apex


can also use the Schedulable interface with batch Apex classes. The following example
implements the Schedulable interface for a batch Apex class called batchable:

1
2 global class scheduledBatchable implements Schedulable {
3
global void execute(SchedulableContext sc) {
4
5 BatchApexExample b = new BatchApexExample();
6
Database.executeBatch(b);

}
Test class for batch Apex
1
2 @isTest
3
private class BatchApexExampleTest {
4
5 static testmethod void test() {
6
7 // Create test accounts to be updated by batch
8
Account[] accList = new List();
9
10 for (Integer i=0;i<400;i++) {
11
12 Account ac = new Account(Name = 'Account ' + i);
13
accList.add(ac);
14
15 }
16
17 insert accList;
18
19
20 Test.startTest();

BatchApexExample b = new BatchApexExample();

Database.executeBatch(b);

Test.stopTest();

// Verify accounts updated

Account[] accUpdatedList = [SELECT Id, Name FROM Account];


System.assert(accUpdatedList[0].Name.Contains('sfdcpoint'));

Best Practices for batch Apex


As with future methods, there are a few things you want to keep in mind when using
Batch Apex. To ensure fast execution of batch jobs, minimize Web service callout times
and tune queries used in your batch Apex code. The longer the batch job executes, the
more likely other queued jobs are delayed when many jobs are in the queue. Best
practices include:

● Only use Batch Apex if you have more than one batch of records. If you don’t
have enough records to run more than one batch, you are probably better off using
Queueable Apex.
● Tune any SOQL query to gather the records to execute as quickly as possible.
● Minimize the number of asynchronous requests created to minimize the chance of
delays.
● Use extreme care if you are planning to invoke a batch job from a trigger. You
must be able to guarantee that the trigger won’t add more batch jobs than the limit.

You might also like