7

Is an AsyncApexJob record inserted immediately at the end of a transaction or is it possible that there is a delay between those two events? I couldn't find firm guarantee in the documentation on that.

As a specific example, I'm calling an @future annotated method in the transaction T1 and I'd like to monitor its progress. It returns void, but I can query the AsyncApexJob table to try to locate it (provided that there are no similar calls at the same time). Since the @future job is only queued after a successful transaction, I can only reach it after the transaction T1 ended, so I'd start another transaction T2 immediately after to monitor it.

The question is whether after means immediately at the end, or there can be some delay d before the record can be found in the AsyncApexJob table?

Illustrated, if there's no delay, then T2 is guaranteed to see the AsyncApexJob record as long as it starts after T1

T1 o------>
          * (AsyncApexJob record inserted by system)
T2         o---->

If there is some delay d, then T2 is not guaranteed to see the record if it starts after T2, but before d has passed.

T1 o----->
         [--d--]* (AsyncApexJob record inserted by system)
T2        o---->
2
  • What about using Queueable Apex? Async Job chaining plus monitoring, both possible with.
    – Marcin Sz.
    Dec 4, 2016 at 2:22
  • @MarcinSz. The job I'm to monitor is not under my control. Otherwise a great idea!
    – ipavlic
    Dec 4, 2016 at 2:49

1 Answer 1

3

I just tested this, and it's available immediately in the same transaction, before the current transaction completes. Obviously, this Id won't be available to other transactions before "final commit," but by the time T2 runs, it is guaranteed to have access to that record.

futureimm.exec();
asyncapexjob j = [select id from asyncapexjob order by createddate desc limit 1];

To avoid false positives, I'd consider restricting the query to just the name or Id of the apex class that gets called, and do so as soon as possible after calling the method to reduce the possibility that another transaction will just happen to complete the same millisecond that you call the query.

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.