9

I have a batch job that updates accounts. There is also an after trigger (just to make life more complicated).

I want that the trigger will not fire during the batch job.

I wrote a global validator class, and trying to control run's with it.

global class Validator_CLS{
    private static boolean blnAlreadyDone = false;

    public static boolean hasAlreadyDone(){ return blnAlreadyDone; }
    public static void setAlreadyDone() { blnAlreadyDone = true; }   
}

Batch works: calls the global class - sets parameter to true

Batch:

public class SF2NSUpdateOpportunityNSId{

    public static void collectData(){

        if(Validator_cls.hasAlreadyDone())
        {
            system.debug('no need to run again');
            return ; 
        }
...... Alot more code here

When trigger fires, it needs to NOT run if parameter is true.

Trigger:

trigger trgSF2NSAccount on Account (after update,after insert) {

    system.debug('trgSF2NSAccount + Validator_cls.hasAlreadyDone ' + Validator_cls.hasAlreadyDone());
    if(Validator_cls.hasAlreadyDone())
    {
        system.debug('no need to run again');
        return ; 
    }
.... A LOT more code here as well

Something is wrong.

The trigger keeps firing

1
  • 1
    are you sure you are not missing setting the value to true during batch like Validator_CLS.setAlreadyDone();
    – snehakem
    Mar 6, 2014 at 13:20

2 Answers 2

30

You can use !system.isBatch() in your trigger to check if it is fired from within a batch or not

3
  • This perfectly resolved my similar situation. Thanks Sven
    – sf_user
    Sep 24, 2015 at 14:59
  • You are welcome. If this answers the question then please mark it as a correct answer. thx Sep 25, 2015 at 7:38
  • Thanks I was also looking for this similar information, so now it means that when you create a trigger on object to trigger from UI while entering data the same will apply while a insert of data happening using a Batch job on that object, if we want to avoid that trigger to be fired during batch we can put suggested condition to avoid that. Thanks So much.
    – Dev G
    Jan 11, 2017 at 20:56
3

System.isSchedulable() might be a more precise method. System.isBatch() is true on both Batchable and Queueable jobs.

1
  • Almost 5 yrs after this answer, it's now System.isScheduled(), and this would only help if the batch was scheduled, not if it was executed directly. Also, the docs now say that isBatch() only returns true for a Queueable in API v35.0 and earlier. There is now System.isQueueable() (and System.isFuture()). developer.salesforce.com/docs/atlas.en-us.apexref.meta/apexref/…
    – MikeA
    Feb 22, 2023 at 19:04

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .