0

If code block 1 and 2 are in the same synchronous execution context , assuming use of the anti-recursion pattern in knowledge article 000133752 below,

assuming I want both code block 1 and 2 to run just once then would i have to declare a new instance of the public Class checkRecursive? See code comments below.

Article 000133752: https://help.salesforce.com/articleView?id=000133752&language=en_US&type=1

Class code:

    public Class checkRecursive{
    private static boolean run = true;
    public static boolean runOnce(){
    if(run){
     run=false;
     return true;
    }else{
        return run;
    }
    }
}

Trigger question:

trigger updateTrigger on anyObject(after update) {

    if(checkRecursive.runOnce())
    {
    //some code block 1
    }

    if(checkRecursive.runOnce()) //this wont run, right?
    {
    //some code block 2
    }

}

If i want both code block 1 and code block 2 to run just once, would i do this?

    trigger updateTrigger on anyObject(after update) {

            if(checkRecursive.runOnce())
            {
            //some code block 1
            }

checkRecursive newCheckRecursiveContext = new checkRecursive();
            if(newCheckRecursiveContext.runOnce()) //this would run, right?
            {
            //some code block 2
            }

        }
2
  • 1
    note that the pattern you cite fails if the transaction has > 200 records such as could occur with anonymous apex, a VF controller, an apex web service, etc. The static variable persists to false across the transaction, even though SFDC splits this up into more than one trigger context of 200 records. Thus records 201+ will never execute.
    – cropredy
    Oct 16, 2017 at 18:14
  • 1
    Is there a reason why you can't simply wrap both code blocks in a single if(checkRecursive.runOnce())?
    – Derek F
    Oct 16, 2017 at 18:21

1 Answer 1

1

You can create a separate runOnce2 method for your purpose.

public Class checkRecursive{
    private static boolean run = true;
    private static boolean run2 = true;
    public static boolean runOnce()
    {
        if(run)
        {
            run=false;
            return true;
        }else
        {
            return run;
        }
    }

    public static boolean runOnce2()
    {
        if(run2)
        {
            run2=false;
            return true;
        }else
        {
            return run2;
        }
    }
}

Trigger

trigger updateTrigger on anyObject(after update) {

    if(checkRecursive.runOnce())
    {
    //some code block 1
    }

    if(checkRecursive.runOnce2()) 
    {
    //some code block 2
    }
}

You must log in to answer this question.

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