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
apexsutherlandapexsutherland 

Detecting that my code is exectuing within a Batch Apex context

So we have an AppExchange app that does all sorts of cool things when a standard Salesforce record (Opportunity, for instance) is inserted, updated, or deleted. However, some of the cool stuff that we're trying to do is breaking batch jobs that our customers run on a regular basis. I won't go into the gory details, suffice it to say that I'd like to be able to detect when my code is running in a Batch Apex context and branch into some different logicy if that is true. I've scoured the Apex documentation and the web, but I can't figure out a reliable way to detect the fact that I'm running in a Batch Apex context. Does anyone know how that might be done?

fgwarb_devfgwarb_dev

I'm looking to do the same thing.  Apex has .IsTest() which is the exact type of functionality that we're looking for, but I can't find .IsBatch() =(

 

My first expectation is to check the DML limits for callouts, right now that is different between contexts.  The DML limit for batches is 1, while in other contexts it is 10.

Mac.AndersonMac.Anderson

This is actually quite easy to do.

 

System.isBatch() // returns true if the currently executing apex code was invoked by a batch

 

You can find the docs here at the below link:

 

http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_methods_system_system.htm

 

Also, in triggers this can be helpful because we do not want to route triggers to methods even if they are "bulkified" due to the limit of 200 records.

tggagnetggagne
This should definitely be marked as the answer.