In Salesforce, a Future Method is an asynchronous method that runs in the background on another thread. The method will execute when Salesforce has the available resources available – otherwise it will sit in a queue and be executed when the resources become available. Future methods are great for executing long-running operations like callouts to external web services or API’s that the user doesn’t need to wait for them to execute.
How to Use Future Methods
Any static method that’s part of a global class can potentially be a future method as long as it returns a void type. Parameters that are passed into the future method must be primitive or basic data types and arrays or collections. Integers, Ids, Doubles, and Strings are examples of primitive data types.
To pass more complex objects you need to serialize them or convert them to a string. I like to use JSON.stringfy for doing this.
When to Use Salesforce Future Methods
Salesforce future methods should be used sparingly because they do have governor limits applied to them. I generally use them when I need to do a callout from an apex trigger or when something can be done in another thread and the user doesn’t need to wait for it. Outbound messages and Batch Apex can also be other good alternatives.
The limits are 200 per 24 hours per full Salesforce license. For an org, with 10 full Salesforce licenses, this means we would have a limit of 2000 future methods a day.
How to Declare a Salesforce Future Methods
Salesforce future methods must be declared in a static method, and return a void data type. Here’s an example of one:
I generally pass in an Id and requery for any data.
Wrapping it Up
In this blog post, we’ve learned a little bit about the future method which can be used any time we don’t necessarily want to make the user wait for anything or when we need to do a callout from an apex trigger.