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
JonSimmons1JonSimmons1 

Stop a trigger from running, if it's already running.

I have a trigger that will update records that will sometimes cause the trigger to be fired a second time. I recall that there is a really easy way to determine if the current running trigger is already running but I can't recall the details. Can anyone help out? Thanks, Jon
spenceSetGetspenceSetGet

I found this searching and it works for me.

 

Create a class names TriggerRunOnce:

 

public with sharing class TriggerRunOnce {

	private static boolean run = true;

 	public static boolean runOnce(){
 
 		if(run){

			run=false;
			
			return true;
 		
 		} else{return run;}
 		
 	}
 	
 	private static testmethod void testTriggerRunOnce(){
 		
 		System.assert(TriggerRunOnce.runOnce(), 'Recursion check failed. Please review OSRUtil recursion logic');

 		System.assert(!TriggerRunOnce.runOnce(), 'Recursion check failed. Please review OSRUtil recursion logic');

 	}
 	
}

 Then in your trigger: 

 

trigger YOUR_TRIGGER on SObject (after delete, after insert, after undelete, 
after update, before delete, before insert, before update) {

   if(TriggerRunOnce.runOnce()) {

      YOUR CODE

   }

}

 

spenceSetGetspenceSetGet

I have now found that if you create a test method that calls this trigger several times.  The test method fails....