Tuesday, October 31, 2017

Future Annotation

Future Annotation

Use the future annotation to identify methods that are executed asynchronously. When you specify future, the method executes when Salesforce has available resources.
For example, you can use the future annotation when making an asynchronous Web service callout to an external service. Without the annotation, the Web service callout is made from the same thread that is executing the Apex code, and no additional processing can occur until the callout is complete (synchronous processing).
Methods with the future annotation must be static methods, and can only return a void type. The specified parameters must be primitive data types, arrays of primitive data types, or collections of primitive data types. Methods with the future annotation cannot take sObjects or objects as arguments.
To make a method in a class execute asynchronously, define the method with the future annotation. For example:
1global class MyFutureClass {
2
3  @future
4  static void myMethod(String a, Integer i) {
5    System.debug('Method called with: ' + a + ' and ' + i);
6    // Perform long-running code
7  }
8}
To allow callouts in a future method, specify (callout=true). The default is (callout=false), which prevents a method from making callouts.
The following snippet shows how to specify that a method executes a callout:
1  @future (callout=true)
2  public static void doCalloutFromFuture() {
3   //Add code to perform callout
4}

Future Method Considerations

  • Remember that any method using the future annotation requires special consideration because the method does not necessarily execute in the same order it is called.
  • Methods with the future annotation cannot be used in Visualforce controllers in either getMethodName or setMethodName methods, nor in the constructor.
  • You cannot call a method annotated with future from a method that also has the future annotation. Nor can you call a trigger from an annotated method that calls another annotated method.

Limitations:
  • 10 future calls per Apex invocation
  • Future calls in a 24 hour period, which is 250,000 or the number of user licenses in your organization multiplied by 200, whichever is greater
  • You cannot call a method annotated with @future from a method that also has the @future annotation


No comments:

Post a Comment

Lightning Inter-Component Communication Patterns

Lightning Inter-Component Communication Patterns If you’re comfortable with how a Lightning Component works and want to build producti...