Wednesday, September 23, 2020

Asyncronous Apex

Asynchronous apex is nothing but to run task or processes in a separate thread, at a later time. Without having user to wait for the task to finish.

The advantages of this approach are :

  • High user efficiency
  • High Scalability
  • Increased Governor & Execution Limits

In short, you don't have to wait in a queue to wait for the task to finish and then execute the second task.

Types of Asynchronous Apex :

  • Future Methods
  • Queuable Jobs
  • Scheduled Apex
  • Batch Apex

When you want to use a future method in salesforce we use @future annotation.

Future annotation (@future) :

1. Use the future annotation to specify that these methods that are executed asynchronously.

2. Methods with future annotation must be static methods.

3. Methods with future annotation can only return a void type.

Let's have a look at the syntax :

============================================

global class classname

{

 @future 

static void methodname(parameters)

{

  //body of the method

 }

}



Future method callouts using @future(callout=true)

To allow callout from the future method annotation needs an extra parameter (callout=true) to indicate that callouts are allowed. Here is example

 

 

 


global class FutureMethodExample {

    @future(callout=true)

    public static void getStockQuotes(String acctName){

        // Perform a callout to an external service

    }

}

IMPORTANT NOTE :

·       No more than 10 method calls per Apex invocation

·       You cannot call a method annotated with the future from a method that also has the future annotation, nor you can call trigger from an annotated method that calls another annotated method.

·       All asynchronous calls made after the startTest method are collected by the system. When stopTest is executed, all asynchronous processes are run synchronously.

·       Use when you want to avoid DML exception.

·       It is used for higher governor limits.

·       To avoid mixed DML exception.

 

LIMITATION :

·       No more than 25 lakh Jobs/24 hrs

·       No more than 50 method calls per apex.

·       One future method cannot call another future method.

BEST PRACTICE OF FUTURE METHODS :

·       Do not call future methods inside for loops.

·       Avoid complex calculations in future methods, else use batch apex.

·       Always consider @future limit is equal to 2x SOQL query.

 

No comments:

Post a Comment

ES12 new Features