3

According to the Execution Governors and Limits the limits for either synchronous or asynchronous transactions can vary, that is why I would like to check whether my current apex transaction is asynchronous. Is there any way in apex to accomplish this?

4

Yes. The System class offers four methods you can call to determine if you're in Asynchronous Apex and, if so, which type:

  • isBatch()
    Returns true if a batch Apex job invoked the executing code, or false if not. In API version 35.0 and earlier, also returns true if a queueable Apex job invoked the code.
  • isFuture()
    Returns true if the currently executing code is invoked by code contained in a method annotated with future; false otherwise.
  • isQueueable()
    Returns true if a queueable Apex job invoked the executing code. Returns false if not, including if a batch Apex job or a future method invoked the code.
  • isScheduled()
    Returns true if the currently executing code is invoked by a scheduled Apex job; false otherwise.
  • 3
    I only wish we had something like System.isAsynchronous() to wrap all four of those into a nice tidy bundle. – sfdcfox Jun 4 '18 at 20:48
  • 1
    I'd created the idea to expose the "Quiddity" as an enum. The motivation being that it would help in scenarios where you care about the execution context/type. – Daniel Ballinger Jun 4 '18 at 21:44
  • Don't forget the mother of all contexts that can have expanded limits: Email services ;-) – Charles T Oct 14 '18 at 15:27
0

The answer that mentions the four methods on the System class is slightly misleading.

As strange as it may seem, scheduled Apex in regards to Limits is considered a "synchronous" context, while the other three mentioned (future, queueable, batch) are truly asynchronous.

There's no cut and dry way to detect whether you are in a synchronous or asynchronous context, but conveniently you usually don't care, you just care about the specific limits right now, and those are easy to get programmatically with the Apex Limits class.

I put together a little demo Apex that helps show the Apex Limits that are enforced in various execution contexts (batch, future, queueable, etc):

https://github.com/open-force/context-detective

enter image description here

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.