Professional Documents
Culture Documents
Helloasyn
Helloasyn
Synchronous Apex :-
Synchronous term means existing or occurring at the same time. Synchronous Apex
means entire Apex code is executed in one single go.
Asynchronous Apex :-
Asynchronous term means not existing or occurring at the same time. Asynchronous
apex is executed when resources are available. So any calling method which calls
Asynchronous apex wont wait for outcome of Asynchronous call. Calling method will
go on further execution in code. And Asynchronous execution happens in separate
thread and then it will return to main program.
An async call is queued up in Salesforce and run on a separate thread of execution.
At this point it becomes decoupled from the calling action. That also means the
calling action won’t block and wait for a response from the asycn call. Using the
future annotation identifies methods that are executed asynchronously. They must
also be static methods. There are some considerations to know when using async
methods.
Synchronous:
In a Synchronous call, the thread will wait until it completes its tasks before
proceeding to next. In a Synchronous call, the code runs in single thread.
Example:
Trigger
Controller Extension
Custom Controller
Asynchronous:
In a Asynchronous call, the thread will not wait until it completes its tasks before
proceeding to next. Instead it proceeds to next leaving it run in separate thread. In a
Asynchronous call, the code runs in multiple threads which helps to do many tasks
as background jobs.
This is a transaction which gets executed in a single thread. Where the called class
has to wait for the other synchronous to finish its execution.
SynchronousClass1.apxc
System.debug('Before Calling');
SynchronousClass2.syncMethod2();
System.debug('After Calling');
}
}
SynchronousClass2.apxc
SynchronousClass1.apxc
System.debug('Before Calling');
AsyncClass.asyncMethod1();
System.debug('After Calling');
}
}
AsyncClass.apxc
@future
public static void asyncMethod1() {
System.debug('Inside future method');
}
}
Future Method
@future
Public static void asyncMethod() {
//future code goes here
}
}
NOTE :-
1) Methods with the future annotation must be static methods
2) can only return a void type
3) The specified parameters must be primitive data types, arrays of primitive data
types, or collections of primitive data types
4) Methods with the future annotation cannot take sObjects or objects as arguments.
5) You can invoke future methods the same way you invoke any other method.
However, a future method can’t invoke another future method
6) No more than 50 method calls per Apex invocation
20th July 2023
In general all the apex classes and apex triggers execute synchronously (execute
immediately).
To execute logic asynchronously keep the logic in an apex method (in a separate
apex class, not in same apex trigger) which is decorated with @future annotation.
SynchronousClass1.apxc
AsyncClass.asyncMethod1();
}
}
AsyncClass.apxc
@future
public static void asyncMethod1() {
PermissionSet perSet = new PermissionSet();
perSet.Label = 'Apex Per Set';
perSet.Name = 'ApexPerSet';
insert perSet;
}
}
@isTest
public class TestClass {
@testSetup
public static void setupTestData() {
System.runAs(u) {
Opportunity opp = new Opportunity();
opp.Name = 'Apex Opportunity';
opp.StageName = 'Closed Won';
opp.CloseDate = System.today();
insert opp;
}
}
@isTest
public static void myMethod() {}
}
Below is the trigger for the scenario that if Account isActive checkbox is false then
delete its child contacts
AccountTrigger.apxt
AccountTriggerHandler.apxc
AsyncClass.asyncMethod1(accountIds);
}
}
AsyncClass.apxc
@future
public static void asyncMethod1(Set<Id> accountIds) {
delete [SELECT Id FROM Contact WHERE AccountId IN : accountIds];
}
}
An HTTP status code is a server response to a browser’s request. When you visit a
website, your browser sends a request to the site’s server, and the server then
responds to the browser’s request with a three-digit code: the HTTP status code.
These status codes are the Internet equivalent of a conversation between your
browser and the server. They communicate whether things between the two are
A-okay, touch-and-go, or whether something is wrong. Understanding status codes
and how to use them will help you to diagnose site errors quickly to minimize
downtime on your site. You can even use some of these status codes to help search
engines and people access your site; a 301 redirect, for example, will tell bots and
people that a page that has moved somewhere else permanently.
The first digit of each three-digit status code begins with one of five numbers, 1
through 5; you may see this expressed as 1xx or 5xx to indicate status codes in that
range. Each of those ranges encompasses a different class of server response.
Use the below link to refer all the status codes and their uses:-
https://restfulapi.net/http-status-codes/
8. What is @future(callout=true)?
To make a Web service callout to an external service or API, you create an Apex
class with a future method that is marked with (callout=true).
If we do not use (callout=true) we’ll get the below error at the time of callouts:-
System.CalloutException: Callout not allowed from this future method. Please enable
callout by annotating the future method. eg: @Future(callout=true)
Remote Site Setting : It is baiscally used to access external website resources from a
Salesforce application for your organization. You can access these external websites
through Visualforce pages, Apex Callout, and via XmlHttpRequest calls.
And it is also used to avoid accessing malicious websites from Salesforce.com, the
website first needs to be registered with remote site settings. Once the site is
registered, it can be used within Salesforce.com.
● Before any Apex callout can call an external site, that site must be registered
in the Remote Site Settings page, or the callout fails. Salesforce prevents
calls to unauthorised network addresses.
● o add a remote site settings:
1. From Setup, enter Remote Site Settings in the Quick Find box, then select
Remote Site Settings.
2. Click New Remote Site.
3. Enter a descriptive term for the Remote Site Name.
4. Enter the URL for the remote site.
5. Optionally, enter a description of the site.
6. Click Save.
If no Remote Site setting are added you’ll get below error while callout:-
System.CalloutException: Unauthorized endpoint, please check
Setup->Security->Remote site settings. endpoint =
http://restapi.adequateshop.com/api/Tourist?page=2
@future(callout=true)
public static void callExternalWebservice() {
By default, test methods don’t support web service callouts, and tests that perform
web service callouts fail.
To prevent tests from failing and to increase code coverage, Apex provides the
built-in WebServiceMock interface and the Test.setMock method. Use
WebServiceMock and Test.setMock to receive fake responses in a test method.
Apex Test Classes will not let us conduct a HTTP callout; therefore, it cannot be used
to test External APIs. However, there is a solution wherein Apex has an interface
called HttpCalloutMock for standard callout tests.
@isTest
public class FutureCalllout_Test {
@isTest
public static void callExternalWebservice() {
Test.startTest();
Test.setMock(HttpCalloutMock.class, new CalloutMock());
FutureCallout.callExternalWebservice();
Test.stopTest();
}
}
@isTest
public class CalloutMock implements HttpCalloutMock{
public HttpResponse respond(HttpRequest req) {
res.setStatusCode(200);
res.setBody('Test JSON Body');
return res;
}
}
Queueable Apex
Queueable jobs are similar to future methods in that they’re both queued for
execution, It has following benefit compared to future methods:
● Getting an ID for your job: When we submit our job by invoking the
System.enqueueJob method, the method returns the ID of the new job. This
ID corresponds to the ID of the AsyncApexJob record. We can use this ID to
identify job and monitor its progress, either through the Salesforce user
interface in the Apex Jobs page, or programmatically by querying your record
from AsyncApexJob.
● Using non-primitive types: 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.
● Chaining jobs: You can chain one job to another job by starting a second job
from a running job. Chaining jobs is useful if you need to do some processing
that depends on another process to have run first.
Implement the Queueable interface to make a Apex class as Queueable class. The
Queueable interface has execute method which must be implemented inside the
class.
System.enqueueJob(new QueueableClass());
OR
The only difference between above two meth iiods is 1st method returns 18 digit ID
and 2nd method returns 15 digit ID.
The below queuable class will query “Test Opportunity Anonymous'' opportunity and
also create it’s parent account.
@isTest
public class QueueableClass_Test {
@testSetup
public static void setupTestData() {
Test.startTest();
Test.stopTest();
}
@isTest
public static void QueueableClass() {
Test.startTest();
System.enqueueJob(new QueueableClass());
Test.stopTest();
List<Account> accList = [SELECT Id FROM Account];
System.assertEquals(1, accList.size());
}
}
Calling one Queueable class from another and so on is called as chaining of jobs.
Maximum 5 chaining is allowed, which means you can chain 5 jobs (1 parent job and
4 child jobs).
Note:-
1. You can call only 1 queueable class from a single queueable class. If more
that 1 queueable is called below error is thrown:-
System.LimitException: Too many queueable jobs added to the queue: 2
2. Only 5 jobs can be chained. If more than 5 are chained below error is thrown:-
System.AsyncException: Maximum stack depth has been reached.
Scenario:- Write a trigger on insert of Account and call Queueable where Queueable
will create a child contact for the account
AccountTrigger.apxt
AccountTriggerHandler.apxc
AccountTriggerQueueable.apxc
conToCreate.add(con);
}
if(!conToCreate.isEmpty()) {
insert conToCreate;
}
}
}
}
}