Find your content:

Search form

You are here

Options for callouts from triggers

 
Share

I need to make some callouts from code that initiates from a trigger. I realize that you can't do a callout directly from a trigger. Currently what I do is make a future call to code that then performs the callout. This has it's own limitations - you can only do 10 future calls per method, so if someone runs code that ends up firing the trigger a bunch of times it can end up crashing the system.

How can these limitations be mitigated? Is there a way for a trigger to fire code that runs outside of the trigger's context (that would circumvent the need for future calls)? That would be ideal but I don't think it's possible.

Is there a way to detect how many future calls have been made within a context (so if you are at the limit you can make some other choices)?

I would even love to be able to batch up all the callouts that need to be made and run them from one future call "at the end" but I don't see how you could detect that.

Having a separate batch that fires every X minutes is the least ideal solution since timeliness is rather important. Being able to make the callouts as soon as possible is important.


Attribution to: Ryan Elkins

Possible Suggestion/Solution #1

The Limit Methods give you the remaining number of future calls

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

Limit.getLimitFutureCalls()

Returns the total number of methods with the future annotation that can be executed (not necessarily )

Since a future method can't invoke another future call, you can't set up a parallel execution context.

What you can do is invoke future methods in batches from the trigger, say passing in batches of 10 ids per future invocation, so that you can benefit from some sort of multiplier effect.

The other alternative will be to write to a staging custom object from the trigger, which is monitored by frequently scheduled apex.


Attribution to: techtrekker

Possible Suggestion/Solution #2

The limits methods are a great suggestion. Also to consider, if the trigger calls code in a class with static variables you can use the static variables to track values throughout the duration of the execution context. (Which may include more than one invocation of the trigger).


Attribution to: Doug B

Possible Suggestion/Solution #3

I've done this before by calling a batch job at the end of the trigger which does all the callouts. You must use care with this method because you can only have 5 batch jobs that can be queued or executing at any time.

See http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_batch_interface.htm#apex_batch_interface


Attribution to: Daniel Hoechst
This content is remixed from stackoverflow or stackexchange. Please visit https://salesforce.stackexchange.com/questions/4084

My Block Status

My Block Content