Preventing Recursive Future Calls

I have a usecase where when an account is updated, an after update trigger is fired. This trigger will call a future method which will call a SOAP API to assign the relevant territory assignment rules. I cannot use Apex to invoke assignment rules; this is a limitation and has been documented below:
https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/sforce_api_header_assignmentruleheader.htm

During this entire process, the assignment rule is assigned properly. The issue is that somehow the trigger is invoked the 2nd time, which is calling the webservice again. And in the logs, I am seeing this exception:

System.CalloutException: Callout loop not allowed

How can I stop the recursive trigger? I checked this link, but seems like this is of no help.
https://blog.jeffdouglas.com/2009/10/02/preventing-recursive-future-method-calls-in-salesforce/

UPDATE: As per the blog, to avoid recursive trigger, I defined a boolean variable

public static boolean inFutureContext = false;

and inside the future method, I am setting the value of this variable to true. In the trigger, this is how I am checking

if (!Territory2Controller.inFutureContext) {
   Territory2Controller.runTerritoryRules(accountIds);
}

So when the trigger is fired for the 1st time, inFutureContext is false. Future method is called where I am setting inFutureContext to true. As API is called, so it will invoke the trigger again. But value of inFutureContext is still false.

Code is provided in the link below:
https://gist.github.com/iamsonal/d5ed44ca4dea45ee6f7002cb361be703

Answer

You can always use the isFuture() method from System class instead of a variable which returns true if the currently executing code is invoked by code contained in a method annotated with future; false otherwise. Link

if (!System.isFuture()) {
   Territory2Controller.runTerritoryRules(accountIds);
}

Also make sure that the web-service is not called from anywhere else.

Attribution
Source : Link , Question Author : snl , Answer Author : manjit5190

Leave a Comment