Friday, October 5, 2018

Future method in salesforce

Future method are annoted with @future annotation which indicates that the method will run
asynchronously(i.e in future when resources are available to it).Normal method runs as soon as
it executes in same thread but future method runs in different thread.Future method always require id's as parameter,Objects are not allowed as there is a possibility that when future method runs data might have changed which can lead to processing on wrong data.

When to use future methods?
.When you are having a callout to an external system.
.To avoid mixed dml error. (Mixed dml error occurs when you try to do dml operations on setup object(Ex: user role) and other objects in the same transaction).

Points to remember while using the future method:

1)The future method is always static with the void return type.
2)The future method always requires id's as parameter, Objects are not allowed.
3)Order of execution is not guaranteed with the future method.
4)When making a callout to external system future method is annotated with(callout=true).
5)future method can’t invoke another future method.

Syntax of future method:

global class myClass{

@future
public static void futureMethodName(list<object> id)
{
// Operations here

}


}

Test class for future method:

To test future method,we need to call future method between test.startTest() and test.stopTest().
When test.startTest() runs data is collected asynchronously and as soon as a test.stopTest runs data collected is run synchronously.

test.startTest();

myClass.futureMethodName(id);

test.stopTest();

How to call a future method from Trigger?

Trigger:


trigger accountAsyncTrigger on Account (after insert, after update) {
  for(Account a: Trigger.new){
    // Invoke the @future method for each Account
    // This is inefficient and will easily exceed the governor limit of
    // at most 10 @future invocation per Apex transaction
    someClass.processAccount(a.id);
   }    
}

Apex:

global class someClass{


  @future
  public static void processAccount(Id accountId) {
// some code here
         }
}


Best way for future method invocation,

trigger accountAsyncTrigger on Account (after insert, after update) {
    //By passing the @future method a set of Ids, it only needs to be
    //invoked once to handle all of the data.
    someClass.processAccount(Trigger.newMap.keySet());
}

TAGS:

Future methods in salesforce,when to use future method in salesforce,test class for future method in salesforce,@future annotation.

No comments:

Post a Comment