[SalesForce] Options for callouts from triggers

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.

Best Answer

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.

Related Topic