Future Methods in Apex Salesforce
Future Apex is used to run processes in a separate thread, at a later time when system resources become available. We need to use the @future
annotation to identify methods that run asynchronously. Trailhead
Future methods are typically used for:
- Operations you want to run in their own thread, when time permits such as some sort of resource-intensive calculation or processing of records.
- Isolating DML operations on different sObject types to prevent the mixed DML error.
- Callouts to external Web services.
If you are making callouts from a trigger or after performing a DML operation, you must use a future or queueable method. A callout in a trigger would hold the database connection open for the lifetime of the callout and that is a “no-no” in a multitenant environment.
Future method consideration:-
- Future methods must be static methods.
- Only return a void type.
- The specified parameters must be primitive data types, arrays of primitive data types, or collections of primitive data types.
- Future methods can’t take standard or custom objects as arguments. A common pattern is to pass the method a
List
of record IDs that you want to process asynchronously - You can invoke future methods the same way you invoke any other method. However, a future method can’t invoke another future method
- The maximum number of future method invocations per a 24-hour period is 250,000 or the number of user licenses in your organization multiplied by 200, whichever is greater.
- To test methods defined with the future annotation, call the class containing the method in a startTest(), stopTest() code block. All asynchronous calls made after the startTest method are collected by the system. When stopTest is executed, all asynchronous processes are run synchronously
What is the benefit of the future method in Salesforce?
- Higher governor limit: A benefit of using future methods is that some governor limits are higher, such as SOQL query limits and heap size limits.
- You can also make use of future methods to isolate DML operations on different sObject types to prevent the mixed DML error.
- Avoid Mixed DML operation: A Mixed DML operation error occurs when you try to persist in the same transaction, change to a Setup Object, and a non-Setup Object.
- Avoid the CPU time limit Error: To avoid the log running talk and avoid the CPU time limit we can use the @Future method in Salesforce. Learn more about Apex CPU Time Limit Exceeded.
- Callout from Trigger: As we know we cannot do the callout from the trigger but we can invoke callouts from triggers by encapsulating the callouts in @future methods.
Syntax of future method:-
global class FutureClass { @future public static void myFutureMethod() { // Perform some operations } }
Future Method with Callout:-
global class FutureMethodWithCallOut
{
@future(callout=true)
public static void getOrderDetail(String oppId)
{
// Perform a callout to an external service
}
}