Introduction
In today’s fast-paced world of business, Salesforce developers often need to execute complex processes without interrupting the user experience.
There are several tools that Salesforce provides which can be used to execute complex business processes and, one of them is the Future Method. If you’re new to the concept or need a refresher, this blog post is for you.
Here, in this blog, we’ll explore:
- What is Future Method?
- Why to use Future Method?
- how to use Future Method in your Salesforce org?
- Best Practises for Future methods.
- Limitations of Future Method
- Future Method vs Queueable Apex.
What is Future Method?
The Future Method is an Asynchronous Apex method in Salesforce, used to execute operations at a later time, rather than executing it immediately in current transaction.
In simpler words, it allows you to “send your tasks into the future,” deferring execution to run independently after the current process finishes.
This method is particularly useful for long-running processes or tasks that don’t need to be completed immediately, such as:
- Web service callouts to external systems,
- Database operations affecting a large volume of data,
- Non-critical updates to records.
By using the Future Method, you can offload these long running processes from the main transaction, which helps in keeping your application responsive and improving the user experience.
Why to use Future Method?
Here are some of the key benefits of using the Future Method in Salesforce:
- Improved User Experience: By deferring time-consuming processes, users aren’t left waiting.
- Reduced Governor Limits: Salesforce limits the number of DML (Data Manipulation Language) statements and queries that can be executed in a synchronous transaction. By using asynchronous processing, you can bypass these limitations, allowing for more extensive operations.
- System Resource Efficiency: Offloading work to asynchronous processes helps to maintain optimal performance, especially when dealing with large volumes of data or high-frequency operations.
How to use the future method in Salesforce?
To create a Future Method, follow these simple steps:
- Define a Static Method: Future Methods must be static and void.
- Annotate with @future: The @future annotation lets Salesforce know this method will run asynchronously.
- Handle Callouts (Optional): If the Future Method involves a callout to an external service, include the (callout=true) parameter.
Basic Example of a Future Method
Here’s a simple example of using the Future Method to update a list of Contact records asynchronously:
public class ContactUpdater {
// Define a Future Method with callout allowed
@future
public static void updateContacts(List contactIds) {
List contactsToUpdate = [SELECT Id, Status__c FROM Contact WHERE Id IN :contactIds];
for (Contact contact : contactsToUpdate) {
contact.Status__c = 'Updated';
}
// Perform the DML operation outside of the main transaction
update contactsToUpdate;
}
}
In this example, the updateContacts method is annotated with @future, indicating that it will execute asynchronously.
When this method (updateContacts) is invoked, Salesforce will not interrupt the current transaction to execute it immediately.
Instead, it processes the method in the background, allowing the specified Contacts to be updated without disrupting the main transaction.
Example 2: Future Method for external callouts
If you need to make a callout to an external system from your Apex class and the method needs to interact with an external API, then include the (callout=true) parameter in the @future annotation.
For Example:
public class AccountCalloutService {
// Enable callout in the Future Method
@future(callout=true)
public static void callExternalService(String accountId) {
Account acc = [SELECT Id, Name FROM Account WHERE Id = :accountId];
// Code for performing HTTP request (callout)
Http http = new Http();
HttpRequest request = new HttpRequest();
request.setEndpoint('https://api.example.com/data');
request.setMethod('POST');
request.setBody('{"accountName": "' + acc.Name + '"}');
HttpResponse response = http.send(request);
// Handle the response if needed
if (response.getStatusCode() == 200) {
// Process successful response
}
}
}
In this example, the callExternalService method makes an HTTP request to an external API, which is allowed by specifying callout=true in the @future annotation.
Salesforce will execute the callout asynchronously without impacting the current transaction.
Best Practises for Future Methods
While Future Methods offer a powerful way to handle asynchronous operations, there are some best practices to keep in mind:
1. Limit Usage: Salesforce allows a maximum of 50 Future calls per Apex invocation. Be cautious when using them within loops or recursive calls.
2. Avoid Chaining: Salesforce does not allow you to call one future method from another future method.
So, do not attempt to call one Future Method from within another. Future Methods are single-level asynchronous processes.
3. Govern Callouts: Future Methods with callout=true can be very useful, but remember that Salesforce has callout limits, so be mindful of these when designing your code.
4. Handle Errors Carefully: Errors in Future Methods won’t propagate back to the caller. Implement logging to catch and monitor issues.
5. Use Future Methods Sparingly in Transactions: Since they don’t execute immediately, avoid depending on them to complete for any logic within the same transaction.
Limitations of the Future Method
While Future Methods are useful, they do come with limitations:
- No Return Values: Future Methods do not return results. If you need feedback, consider using other asynchronous tools like Queueable Apex.
- Single-Level Asynchronicity: Future Methods cannot call other Future Methods, Queueables, or Batch Apex. They’re restricted to a single level of asynchronicity.
- Limited Monitoring: Salesforce provides limited tools to track Future Methods once they’ve been scheduled. Consider logging results to custom objects for better tracking.
Future Method vs Queueable Apex
In many cases, Queueable Apex is a more robust alternative to Future Methods.
Queueable Apex provides additional features like:
- Chaining, allowing one job to trigger another.
- Monitoring, giving developers more control over job completion.
- Enhanced governor limits, which help when dealing with complex or resource-intensive operations.
In general, if your logic is simple and doesn’t require chaining or advanced handling, Future Methods can be the ideal solution.
However, for more complex asynchronous operations, Queueable Apex is usually the better choice.
Conclusion
The Future Method in Salesforce is a valuable tool for managing asynchronous operations, enabling developers to offload complex tasks and optimize the user experience.
By understanding when and how to use it, you can create faster, more efficient Salesforce applications that improve productivity.
Remember to apply best practices, handle callouts carefully, and understand the limitations to maximize the potential of the Future Method.
Happy Coding!