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?
3 Answers
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.
-
4I only wish we had something like
System.isAsynchronous()
to wrap all four of those into a nice tidy bundle.– sfdcfoxJun 4, 2018 at 20:48 -
1I'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. Jun 4, 2018 at 21:44
-
Don't forget the mother of all contexts that can have expanded limits: Email services ;-) Oct 14, 2018 at 15:27
How about something like below?
public static Boolean isAsynchronous(){
return (Limits.getLimitCpuTime() == 60000);
}
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):