Salesforce Asynchronous Apex | @future Methods

Salesforce Asynchronous Apex 


What is Asynchronous 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.

What does it mean ?
Let's consider a real-time scenario, We always have pending tasks to do on every weekend like washing clothes, buying weekly vegetables, going out for a movie etc. But if I will first wash cloths and then go out for vegetables then come back home and then in the evening I can go for a movie, isn't it will take too long for me to go for movie right ??

But what if I will put my clothes in the washing machine and set time then go out in the market with food and vegetable wishlist and give that list to the store and then go for a movie, then while coming back I will collect vegetable and food from the store and come back to home and lastly get out washed clothes from washing machine. 

How it will help ?
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.
Hence we use asynchronous apex in salesforce to do the same.

Types of Asynchronous Apex :
  • Future Methods
  • Queuable Jobs
  • Scheduled Apex
  • Batch Apex
In this episode, we will discuss how to use Future Methods in salesforce.
So let's get started...

Future Methods :
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
 }
}
============================================

Let's use this syntax in the example :

For example :
============================================
global class MyFutureClass
{
 @future 
static void myMethod(String a, Integer i)
 {
   system.debug('Method called with :'+a+'and'+i');
//do callout, other long running code.
 }
}
============================================

4. @future (callouts=true), this indicates that these future methods can use callouts.

For Example :
============================================
@future(callout=true)
public static void docalloutfromfuture()
{
  //Add code to perform callout
} 
============================================

5. @future(callouts=true) this is used to prevent a method from making callouts.

6. The parameters specified must be primitive data types, arrange of primitive data types or collections of primitive data types.

7. Methods with the future annotation can not take sObjects or objects as arguments.

Important: If you want to pass the sObject/Apex class object as parameters in the @future methods. 

Then follow the following steps :

STEP 1: First create Apex Class Address (considering address example)
============================================
public with sharing class Address
{
 public string street{set; get;}
 public string city{set; get;}
 public string state{set; get;}
 public string zip{set; get;}

 public Address(String s, String c, String st, String z)
 {
  Street = s;
  City = c;
  State = st;
  zip =z;
 }
}
============================================

STEP 2: Create Address Future Class
1. Within the constructor create object for Address class and serialize the objects.
2. Create a future method call future(string) with string as parameters in the methods deserialize the string to objects and use them.
============================================
public with sharing class AddressFuture
{
 public AddressFuture()
 {
  List<String> addresses = new List<String>();

AddressHelper ah1 = new AddressHelper('1 hase st', 'san Fransisco', 'CA', '94105');

AddressHelper ah2 = new AddressHelper('2 hase st', 'san Fransisco', 'CA', '94105');

AddressHelper ah3 = new AddressHelper('3 hase st', 'san Fransisco', 'CA', '94105');

//serialize my objects ah1, ah2, ah3 
 addresses.add(JSON.serialize(ah1));
 addresses.add(JSON.serialize(ah2));
 addresses.add(JSON.serialize(ah3));

callfuture(addresses); //Invoke the future method by passing a string addresses where it is serialized form of Apex class objects.
 } 

 @future
 static void callfuture(List<string> addresses)
 {
  Address currAddress = null;
  for(string ser: addressesser)
  {
   currAddress = (Address)JSON.deserialize(ser, AddressHelper.class);
   System.debug('Deserialized in future : '+ currAddress.street);
  } 
 }
}
============================================

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.

In this way, we can use future annotation to avoid the exception and efficiently use perform tasks and processes.
In the next episode, we will discuss the remaining types of asynchronous apex in salesforce.


WOHOOO !! YOU HAVE JUST COMPLETED SALESFORCE ASYNCHRONOUS EPISODE
If you like this salesforcekid learning platform please let me know in the Comment section...Also, Share with your salesforce folks wish you 
Happy learning ☁️⚡️ (Learn. Help. Share.)

<< PREVIOUS                                          NEXT >>

Salesforce Asynchronous Apex by salesforce kid on play store

Salesforce Asynchronous Apex | @future Methods Salesforce Asynchronous Apex | @future Methods Reviewed by on Rating: 5

No comments:

HELP !! SHARE !! SUGGEST !!

Powered by Blogger.