3

in my apex code I need to do some calculation only when future method has executed I tried below code to check if future method has executed:

public static void anotherMethod() {
while('Completed' != checkFutureMethod()) {
            checkFutureMethod();
         }

// need to do something here only when future method has executed
}

 private static string checkFutureMethod() {
        string asyncApexStatus;
        for(AsyncApexJob asyncApex : [select Status From AsyncApexJob where ApexClass.Name = 'classname']) {
                                 asyncApexStatus = asyncApex.Status; 
                              }
        return asyncApexStatus;

    }

but still the above doesn't wait future method to finish, please suggest.

7

First, asynchronous methods will never even start until the previous transaction commits, so any wait loop would need to be asynchronous itself. Secondly, if you need the status of an asynchronous call, use Queueable instead. Unlike future methods, Queueable methods provide a JobId, which you can query against to see if the unit has executed, and if it did so successfully.

MyQueueable someQueueable = new MyQueueable();
Id jobId = System.enqueueJob(someQueueable);

// ... some time later ... //
AsyncApexJob job = [SELECT Status FROM AsyncApexJob WHERE Id = :jobId];

Remember, you must allow the current transaction to complete before the asynchronous code can run, so you'll need a mechanism to wait, such as using a Visualforce page with apex:actionPoller.

Presumably, your code will find the first future method ever to be called by that class, thus will immediately return as completed. There's no way to determine which future method is which with 100% accuracy, which is one reason why Queueable was invented.

|improve this answer|||||
  • Thank you so much for responding, so should I keep running SOQL on asyncApex until I get completed status the way I was doing with the future in question? – gs650x Dec 27 '19 at 18:13
  • 1
    @gs650x You'll likely hit governor limits if you try this. You'll need to design a way to check back later without the loop. I'd need to know more about what the context for what you're trying to do (e.g. Visualforce, trigger, etc) to provide an appropriate alternative solution. – sfdcfox Dec 27 '19 at 18:16
  • it is LWC and on a click of button it updates on so many objects and to avoid governor limit it is future method. – gs650x Dec 27 '19 at 18:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.