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.

To make a method in a class execute asynchronously, define the method with the future annotation. For example:

global class MyFutureClass {

  @future 
  static void myMethod(String a, Integer i) {
    System.debug('Method called with: ' + a + ' and ' + i);
    //do callout, other long running code 
    
  }
}

The following snippet shows how to specify that a method executes a callout:

  @future (callout=true)
  public static void doCalloutFromFuture() {
   //Add code to perform callout 
    
}

You can specify (callout=false) to prevent a method from making callouts.

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.

Methods with the future annotation have the following limits:

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.

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.

The getContent and getContentAsPDFPageReference methods cannot be used in methods with the future annotation.

For more information about callouts, see Invoking Callouts Using Apex.

© Copyright 2000–2012 salesforce.com, inc. All rights reserved.
Various trademarks held by their respective owners.