Find your content:

Search form

You are here

"Chaining" @future calls

 
Share

How is the chaining of future call achieved in example from Dan Appleman book http://advancedapex.com/samplecode/ ? I am trying to insert 200/220 records and see that only one future is forced.

public static void GoingAsync3(List<Solution> solutionlist, Map<ID, Solution> oldmap, Boolean isInsert)
    {
        if(AlreadyProcessed) return;
        AlreadyProcessed = true;
        for(Solution sl:solutionlist)
        {
            if(isInsert || sl.SolutionNote!= oldmap.get(sl.id).SolutionNote) sl.TranslationPending__c = true; 
        }
        ThirdAttemptRequestAsync();
    }


public static void ThirdAttemptRequestAsync()
    {
        GoAsyncHelper__c asynchelper = GetAsyncHelper();
        if(ThirdAttemptAsyncRequested) return;  // Already fired a request in this context
        if(asynchelper.AsyncPending__c) return; // Someone already requested async operation

        asynchelper.AsyncPending__c = true;
        Database.Update(asynchelper);

        if(!System.isFuture() && !System.isBatch() && !System.isScheduled())
        {
            ThirdAttemptAsyncRequested = true;
            ThirdAttemptAsync();
        }
    }

@future
    private static void ThirdAttemptAsync()
    {
        GoAsyncHelper__c asynchelper = GetAsyncHelper();
        if(asynchelper.AsyncPending__c)
        {   // Clear any pending request
            asynchelper.AsyncPending__c = false;
            Database.Update(asynchelper);
        }

        ThirdAttemptSync();
    }

    public static void ThirdAttemptSync()
    {
        Integer availablecallouts = Limits.getLimitCallouts() - Limits.getCallouts();
        if(availablecallouts < 2)
        {
            ThirdAttemptRequestAsync();
            return;
        }
        List<Solution> solutionstoupdate = [SELECT ID, SolutionNote, SolutionSpanish__c from Solution where LastModifiedDate > :DateTime.Now().addHours(-24) And TranslationPending__c = true LIMIT :availablecallouts];
        for(Solution sl: solutionstoupdate) sl.SolutionSpanish__c = SimulateTranslationCallout(sl.SolutionNote);
        update solutionstoupdate;

        if(solutionstoupdate.size()== availablecallouts)
        {
            ThirdAttemptRequestAsync();
        }
    }

    public static GoAsyncHelper__c GetAsyncHelper()
    {
        GoAsyncHelper__c theobject = GoAsyncHelper__c.getInstance('default');
        if(theobject==null) 
        {
            theobject = new GoAsyncHelper__c();
            theobject.name = 'default';
            theobject.AsyncPending__c = false;
            Database.Insert(theobject);
        }
        return theobject;
    }

Attribution to: Natallia
This content is remixed from stackoverflow or stackexchange. Please visit https://salesforce.stackexchange.com/questions/33472

My Block Status

My Block Content