The @future
annotation (pronounced as at future) is, perhaps, the simplest method of asynchronous code execution on the Salesforce1 platform. The @future
, is a method annotation that makes the method run asynchronously at some point in the near future. Generally, this happens quite quickly, but no time guarantees are established annotation methods as @future
is fantastically useful, but has a number of caveats and limitations that developers must remain mindful of:
@future
can only accept primitive parameter types. String, Integer, and so on, are your only options.@future
. In other words, an @future
annotated method cannot be called from another @future
annotated method. This is especially crucial to remember when your @future
method may result in a trigger firing. If an @future
method fires a trigger, that trigger cannot in turn call other @future
annotated methods.@future
cannot return a value—they must have a Void
return type—and they must be declared static.These caveats and limitations should not deter you from using the @future
annotation. Indeed, the biggest limitation that—parameters must be primitives—can be easily overcome with a bit of clever programming. For example, while an @future
method cannot take sObjects
for parameters, it can accept a string. Even a string resulting from the JSON serialization of an sObject, or list of sObjects. The following is an example of this pattern:
Public with sharing class Examples { @future Public public Static Void void myAtFutureMethod(String jsonStringOfAccount){ Account a = (Account) JSON.deserialize(jsonStringOfAccount, Account.class); //do work with your sObject } }
One of the best features of the @future
annotated methods is that they can be used to execute callouts. If, for instance, you are integrating with an external API that takes a while to return, you can make the callout from an @future
method rather than, say, your Visualforce controller. To enable the callout feature of the @future
methods, append the option callout=true
to your @future
annotation. Methods annotated with the @future
annotations with callouts work best when you are creating net-new related records. If you are editing an existing record, you will likely end up in a situation where the @future
method executes the DML to update the record. If there are triggers calling the @future
methods set on the same object—a common enough occurrence— you will inadvertently end up throwing an exception trying to execute an @future
method from within an @future
context.
In general, use the @future
annotations on methods where the situation is truly fire-and-forget. Running code in a future context resets the governor limits by creating a new Apex context to run them in. If your code is encapsulated, such that you can execute a single method in a different Apex context, then it is fine to annotate it as @future
. Be careful calling methods with the @future
annotation from triggers.
18.188.10.1