Thursday 3 May 2012

Future Methods in Salesforce

Future annotation is used 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).

 global class MyFutureClass {  
 @future   
   public static void myMethod() {  
     EmailClass.SendEmailNotification();  
     //do callout, other long running code  
   }  
 }  
Email Class
 global class EmailClass{  
   WebService static void SendEmailNotification() {  
     //create a mail object to send a single email.  
     Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();  
     //set the email properties  
     mail.setToAddresses(new string[] {'wahib.idris@xyz.com'});  
     mail.setSenderDisplayName('SF.com Email Agent');  
     mail.setSubject('A new reminder');  
     mail.setHtmlBody('Password');  
     //send the email  
     Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail } );  
   }  
 }  

Points to Remember about future method :

  1. No more than 10 method calls per Apex invocation.
  2. The specified parameters must be primitive data types, arrays of primitive data types, or collections of   primitive data types.
  3. Methods with the future annotation cannot take sObjects or objects as arguments.
  4. Methods with the future annotation cannot be used in Visualforce controllers in either getMethodName or setMethodName methods, nor in the constructor.
  5. 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.
  6. @future(callout = true) means that the method has ability to invoke external web services.

4 comments:

  1. its really very understanble view

    ReplyDelete
  2. Really awesome blog. Your blog is really useful for me. Thanks for sharing this informative blog. Keep update your blog.
    J2EE training in chennai

    ReplyDelete