function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
smillssmills 

How to Monitor Apex Jobs Status Programatically?

I am making future calls from APEX code and need to know when the calls complete so I can do other processing. If I use the GUI of Salesforce I can go to the Setup area and under 'Monitoring', I can use the 'Apex Jobs' selection to see the job is processing and if it completed.

 

Reason being, my APEX code breaks the future calls up into batches.  I usually end up doing 3 future calls, but need to know all three have completed before I can continue with some DML operations.


How can I get the future call status information programatically within my code?

 

smillssmills

UPDATE: I do see there is AsyncApexJob object that I can query, but don't see how to get the JobID for the future call since the future call is defined with a void return value, as per salesforce. 

 

Also, since two users could call instantiate the Apex code that calls the 3 future calls, then I need to be able to get the group of future calls per instantiation to check when/if they are completed successfully, and if needed process the completed/failures.

kibitzerkibitzer
You could make a query like this after you make the future call:
List<AsyncApexJob> jobs = [Select ID, Status, MethodName, ApexClass.Name from AsyncApexJob where ApexClass.Name='theclass' And MethodName = 'themethod' And JobType='Future' and Status = 'Queued' ];
You could add additional where terms to filter on the current user as the createbyid field, and filter on the createddate field to get objects created within the past few seconds (or to be really accurate, store a datetime value captured before the future call and use that in the filter.

This should give you the job IDs of those async jobs.

It won't be perfect - there are some concurrency issues - in the unlikely event that an async job runs in the brief time between creating the future call and querying the record, or if you have multiple threads running with the same owner and they just happen to create future calls at the same time, you may capture future calls created by a different execution context.

This is an answer to a specific question - I'd encourage you to think at a higher level about the overall architecture to come up with a design that is tolerant of those kinds of concurrency issues.
Cloud_forceCloud_force
you can use below 2 lines. 
List<AsyncApexJob> myrunningjob = [Select Id, Status, ApexClass.Name From AsyncApexJob where ApexClassId =: yourclassid order by CreatedDate DESC limit 1];
System.debug('###### running job status is: 'myrunningjob[0].status];

this will give you latest running job status.

thanks,http://www.forcexplore.com/2014/01/salesforce-interview-questions-2.html