+ Start a Discussion
Deepu sfdcDeepu sfdc 

future method examples

Can you give me the examples of Future method and  Asynchronous apex ?

Thanks in Advance
Best Answer chosen by Deepu sfdc
HARSHIL PARIKH AKA:GovindHARSHIL PARIKH AKA:Govind

Hi Deepu sfdc,

Let's say you are tracking a State, County, and Country information on Lead object as a custom fields such as Custom_State__c, Custom_County__c, and Custom-Country__c. Also, you have additional custom field named Custom_Zip_Code__c (a number field).

Your requirment is that whenever user enters a lead record with a value on Custom_Zip_Code__c field, all other fields (Custom_State__c, Custom_County__c, and Custom-Country__c) should be automatically updated with a use of FUTURE METHOD. Why Future method and not trigger directly? It's because your business requirements says so, or you are not in hurry to update these fields, or you are looking for a greater sets of government limits etc.. The reason can be anything.

Now, imagine you have a seperate object in salesforce named Master Address (this object has nothing to do with Lead object means no relationship at all) which contains information about all zip codes in US with their appropriate State, County and Country info.

Something like below.
Zip Code         State                County                       Country
1000              New Jersey        Morris                        United States
2000               New York          Chester                      United States
45000              Vermont            Vermont County         United States
+++++             +++++++             ++++++++++++++         ++++++++++
+++++             +++++++             ++++++++++++++         ++++++++++
up to very last zip code in US :)
+++++             +++++++             ++++++++++++++         ++++++++++
+++++             +++++++             ++++++++++++++         ++++++++++


Scenario:
Example: If lead is entered with name Mark Hunt with zip code as 45000 then Custom State, Custom County, and Custom Country should be updated as VT, Vermont County, and United States. Just imagine that 45000 is a zip code for vermont even though.. its probably not :) ). Hope this is making sense so far..


Now here comes the trigger + Future method magic. Below trigger calls a Future method class.

Trigger Code:

Trigger LeadCustomAddress on Lead (After Insert, After UnDelete, Before Update) {
	 
    List<Id> flaggedLeadIds = New List<Id>();
    Set<String> zipCodes = New Set<String>(); 
    
    If(LeadCustomAddress_ProcessControl.visited == False)
    {
        If(Trigger.IsInsert || Trigger.IsUnDelete || Trigger.IsUpdate)
        {
            For(Lead Ld: Trigger.New)
            {
                If(Ld.Custom_Zip_Code__c != NULL && Ld.Custom_State__c == NULL
                                                 && Ld.Custom_County__c == NULL
                                                 && Ld.Custom_Country__c == NULL)
                {
                       flaggedLeadIds.add(Ld.Id); 
                       zipCodes.add(Ld.Custom_Zip_Code__c);
                }
            }
        }
        LeadCustomAddress_FutureClass.LeadCutomAddress_FutureMethod(flaggedLeadIds, zipCodes); 
    }
   
    
}
 

FUTURE METHOD:
 

Public class LeadCustomAddress_FutureClass {
	 
    @Future
    Public static Void LeadCutomAddress_FutureMethod(List<Id> leadIds, Set<String> leadZips){
        
        List<Lead> comingLeads = [Select Id, Custom_Zip_Code__c, Custom_State__c, Custom_County__c, Custom_Country__c
                                 		FROM Lead WHERE Id =: leadIds];
        
        List<Master_Address__c> allNeededMasterAddressInfo = [Select Id, Zip_Code__c, State__c, County__c, Country__c
                                                             		FROM Master_Address__c
                                                              			WHERE Zip_Code__c =: leadZips];
        
        //system.debug('*****The size of comingLeads is: ' + comingLeads.size());
        system.debug('*****The size of allNeededMasterAddressInfo is: ' + allNeededMasterAddressInfo.size());
        
        List<Lead> leadFinalListToUpdate = New List<Lead>();
        For(Lead EveryLead : comingLeads)
        {
            If(EveryLead.Custom_Zip_Code__c != NULL && EveryLead.Custom_State__c == NULL
              								 		&& EveryLead.Custom_County__c == NULL
                                             		&& EveryLead.Custom_Country__c == NULL)
            {
                For(Master_Address__c EveryMasterRecord : allNeededMasterAddressInfo)
                {
                    If(String.valueof(EveryMasterRecord.Zip_Code__c) == String.valueof(EveryLead.Custom_Zip_Code__c))
                    {
                    	EveryLead.Custom_State__c =  EveryMasterRecord.State__c;
                        EveryLead.Custom_County__c =  EveryMasterRecord.County__c;
                        EveryLead.Custom_Country__c =  EveryMasterRecord.Country__c;
                    }
                }    
            }
            leadFinalListToUpdate.add(EveryLead);
        }
        /*
        system.debug('Updating Leads Info: Zip Code Is: ' + leadFinalListToUpdate[0].Custom_Zip_Code__c
                    					   + 'State Is: ' + leadFinalListToUpdate[0].Custom_State__c
                    					   + 'County Is: ' + leadFinalListToUpdate[0].Custom_County__c
                    					   + 'Country Is: ' + leadFinalListToUpdate[0].Custom_Country__c);*/
        
        //update leadFinalListToUpdate;
        
        try{
            If(!leadFinalListToUpdate.isEmpty())
            {
                LeadCustomAddress_ProcessControl.visited = TRUE;
                update leadFinalListToUpdate;
            }
        }Catch(Exception e){
            system.debug('Thrown Exception For LeadCutomAddress_FutureMethod Is: ' + e.getmessage());
        }
        
    }
}
What does an above code does?
-- First it identifies which leads is coming with zip code and no information on state, county and country field. If identified, trigger code gets called..--- then trigger code calls future method to update State, County and Country field appropriatly.

What would happen if there is no FUTURE method in this case:
-- Trigger would fire and update State, County and Country info right a way. But if you use Future method then it will update in future. Of course, not after 2 weeks but after several minutes or several seconds... whenever resources become available.


Hope everything is making sense so far. Would you like to see this in action? Here we go...

1) Inserting a record with zip but no values on any other fields...

User-added image

2) Saving Record. At this time trigger is called and future method is called as well...But nothing happens since resources are not available.

User-added image

3) In about a minute or so the resources becomes availabe and Voila!!!

User-added image





Hope this example helps and if this answers your question then kindly mark it as BEST ANSWER!
         



 

All Answers

NagendraNagendra (Salesforce Developers) 
Hi Deepu,

What is Future Method:

A future method runs in the background, asynchronously. You can call a future method for executing long-running operations, such as callouts to external Web services or any operation you'd like to run in its own thread, on its own time.

When to use Future Method:

If you want to make the execution of the apex program to run asynchronously then we make use of future method.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.

Apex class with Future Method:
public class AccountProcessor 
{
  @future
  public static void countContacts(Set<id> setId) 
  {
      List<Account> lstAccount = [select id,Number_of_Contacts__c , (select id from contacts ) from account where id in :setId ];
      for( Account acc : lstAccount )
      {
          List<Contact> lstCont = acc.contacts ;
          
          acc.Number_of_Contacts__c = lstCont.size();
      }
      update lstAccount;
  }
}
Test class for the above:
@IsTest
public class AccountProcessorTest {
    public static testmethod void TestAccountProcessorTest() 
    {
        Account a = new Account();
        a.Name = 'Test Account';
        Insert a;

        Contact cont = New Contact();
        cont.FirstName ='Bob';
        cont.LastName ='Masters';
        cont.AccountId = a.Id;
        Insert cont;
        
        set<Id> setAccId = new Set<ID>();
        setAccId.add(a.id);
 
        Test.startTest();
            AccountProcessor.countContacts(setAccId);
        Test.stopTest();
        
        Account ACC = [select Number_of_Contacts__c from Account where id = :a.id LIMIT 1];
        System.assertEquals ( Integer.valueOf(ACC.Number_of_Contacts__c) ,1);
  }
  
}
For more information refer to the below link. Hope this helps.

Kindly mark this as solved if the information was helpful.

Thanks,
Nagendra


 
Deepu sfdcDeepu sfdc
Hi Nagendra,

Thanks for the reply.
The example you given is already available in google. Can you please give me one more example so that i can understand clearly.

Regards,
Deepu
HARSHIL PARIKH AKA:GovindHARSHIL PARIKH AKA:Govind

Hi Deepu sfdc,

Let's say you are tracking a State, County, and Country information on Lead object as a custom fields such as Custom_State__c, Custom_County__c, and Custom-Country__c. Also, you have additional custom field named Custom_Zip_Code__c (a number field).

Your requirment is that whenever user enters a lead record with a value on Custom_Zip_Code__c field, all other fields (Custom_State__c, Custom_County__c, and Custom-Country__c) should be automatically updated with a use of FUTURE METHOD. Why Future method and not trigger directly? It's because your business requirements says so, or you are not in hurry to update these fields, or you are looking for a greater sets of government limits etc.. The reason can be anything.

Now, imagine you have a seperate object in salesforce named Master Address (this object has nothing to do with Lead object means no relationship at all) which contains information about all zip codes in US with their appropriate State, County and Country info.

Something like below.
Zip Code         State                County                       Country
1000              New Jersey        Morris                        United States
2000               New York          Chester                      United States
45000              Vermont            Vermont County         United States
+++++             +++++++             ++++++++++++++         ++++++++++
+++++             +++++++             ++++++++++++++         ++++++++++
up to very last zip code in US :)
+++++             +++++++             ++++++++++++++         ++++++++++
+++++             +++++++             ++++++++++++++         ++++++++++


Scenario:
Example: If lead is entered with name Mark Hunt with zip code as 45000 then Custom State, Custom County, and Custom Country should be updated as VT, Vermont County, and United States. Just imagine that 45000 is a zip code for vermont even though.. its probably not :) ). Hope this is making sense so far..


Now here comes the trigger + Future method magic. Below trigger calls a Future method class.

Trigger Code:

Trigger LeadCustomAddress on Lead (After Insert, After UnDelete, Before Update) {
	 
    List<Id> flaggedLeadIds = New List<Id>();
    Set<String> zipCodes = New Set<String>(); 
    
    If(LeadCustomAddress_ProcessControl.visited == False)
    {
        If(Trigger.IsInsert || Trigger.IsUnDelete || Trigger.IsUpdate)
        {
            For(Lead Ld: Trigger.New)
            {
                If(Ld.Custom_Zip_Code__c != NULL && Ld.Custom_State__c == NULL
                                                 && Ld.Custom_County__c == NULL
                                                 && Ld.Custom_Country__c == NULL)
                {
                       flaggedLeadIds.add(Ld.Id); 
                       zipCodes.add(Ld.Custom_Zip_Code__c);
                }
            }
        }
        LeadCustomAddress_FutureClass.LeadCutomAddress_FutureMethod(flaggedLeadIds, zipCodes); 
    }
   
    
}
 

FUTURE METHOD:
 

Public class LeadCustomAddress_FutureClass {
	 
    @Future
    Public static Void LeadCutomAddress_FutureMethod(List<Id> leadIds, Set<String> leadZips){
        
        List<Lead> comingLeads = [Select Id, Custom_Zip_Code__c, Custom_State__c, Custom_County__c, Custom_Country__c
                                 		FROM Lead WHERE Id =: leadIds];
        
        List<Master_Address__c> allNeededMasterAddressInfo = [Select Id, Zip_Code__c, State__c, County__c, Country__c
                                                             		FROM Master_Address__c
                                                              			WHERE Zip_Code__c =: leadZips];
        
        //system.debug('*****The size of comingLeads is: ' + comingLeads.size());
        system.debug('*****The size of allNeededMasterAddressInfo is: ' + allNeededMasterAddressInfo.size());
        
        List<Lead> leadFinalListToUpdate = New List<Lead>();
        For(Lead EveryLead : comingLeads)
        {
            If(EveryLead.Custom_Zip_Code__c != NULL && EveryLead.Custom_State__c == NULL
              								 		&& EveryLead.Custom_County__c == NULL
                                             		&& EveryLead.Custom_Country__c == NULL)
            {
                For(Master_Address__c EveryMasterRecord : allNeededMasterAddressInfo)
                {
                    If(String.valueof(EveryMasterRecord.Zip_Code__c) == String.valueof(EveryLead.Custom_Zip_Code__c))
                    {
                    	EveryLead.Custom_State__c =  EveryMasterRecord.State__c;
                        EveryLead.Custom_County__c =  EveryMasterRecord.County__c;
                        EveryLead.Custom_Country__c =  EveryMasterRecord.Country__c;
                    }
                }    
            }
            leadFinalListToUpdate.add(EveryLead);
        }
        /*
        system.debug('Updating Leads Info: Zip Code Is: ' + leadFinalListToUpdate[0].Custom_Zip_Code__c
                    					   + 'State Is: ' + leadFinalListToUpdate[0].Custom_State__c
                    					   + 'County Is: ' + leadFinalListToUpdate[0].Custom_County__c
                    					   + 'Country Is: ' + leadFinalListToUpdate[0].Custom_Country__c);*/
        
        //update leadFinalListToUpdate;
        
        try{
            If(!leadFinalListToUpdate.isEmpty())
            {
                LeadCustomAddress_ProcessControl.visited = TRUE;
                update leadFinalListToUpdate;
            }
        }Catch(Exception e){
            system.debug('Thrown Exception For LeadCutomAddress_FutureMethod Is: ' + e.getmessage());
        }
        
    }
}
What does an above code does?
-- First it identifies which leads is coming with zip code and no information on state, county and country field. If identified, trigger code gets called..--- then trigger code calls future method to update State, County and Country field appropriatly.

What would happen if there is no FUTURE method in this case:
-- Trigger would fire and update State, County and Country info right a way. But if you use Future method then it will update in future. Of course, not after 2 weeks but after several minutes or several seconds... whenever resources become available.


Hope everything is making sense so far. Would you like to see this in action? Here we go...

1) Inserting a record with zip but no values on any other fields...

User-added image

2) Saving Record. At this time trigger is called and future method is called as well...But nothing happens since resources are not available.

User-added image

3) In about a minute or so the resources becomes availabe and Voila!!!

User-added image





Hope this example helps and if this answers your question then kindly mark it as BEST ANSWER!
         



 

This was selected as the best answer
Akshata ShahAkshata Shah
Hey Nagendra,
Will help me for this to write Future calls.

I want to calaculate Total Leaves for the particular month taken by Resource
I have 3 custom object
1 ) Resource__c
2 ) Month__c has master detail with Resource__c,Number field Leaves_Taken__c
3) Leave__c has lookup with Resource__c , Leave_Date__c, picklist Decision__c(Approved/Rejected).

Need to create  future call & write a function which looks at all Leaves & each time calculates & updates Month__c object records if there is a change.

If the Decision__c is Approved then want to achieve following condition.
1) If Leaves are taken on both Friday & Monday, then 4 leaves to be added in Leaves_Taken__c field ( In Month__c object) for that particulr Month.
2) If Leaves are taken from Monday to Friday, then 9 Leaves to be added in Leaves_Taken__c field ( In Month__c object) for that particulr Month.
3) If single day taken leaves then 1 to be added in the Leaves_Taken field for that Month.
4) On Delete of Leave__c decrement will happen in Leaves_Taken__c.
5) On update of Leave__c repested action will happen.(increment/decrement).

Regards,
Akshata
Akshata ShahAkshata Shah
Hii @HARSHIL PARIKH AKA:Govind

Please help me for future calls for below condition.
I want to calaculate Total Leaves for the particular month taken by Resource
I have 3 custom object
1 ) Resource__c
2 ) Month__c has master detail with Resource__c,Number field Leaves_Taken__c
3) Leave__c has lookup with Resource__c , Leave_Date__c, picklist Decision__c(Approved/Rejected).

Need to create  future call & write a function which looks at all Leaves & each time calculates & updates Month__c object records if there is a change.

If the Decision__c is Approved then want to achieve following condition.
1) If Leaves are taken on both Friday & Monday, then 4 leaves to be added in Leaves_Taken__c field ( In Month__c object) for that particulr Month.
2) If Leaves are taken from Monday to Friday, then 9 Leaves to be added in Leaves_Taken__c field ( In Month__c object) for that particulr Month.
3) If single day taken leaves then 1 to be added in the Leaves_Taken field for that Month.
4) On Delete of Leave__c decrement will happen in Leaves_Taken__c.
5) On update of Leave__c repested action will happen.(increment/decrement).

Regards,
Akshata