Considerations for invoking a future method from trigger
While developing triggers, there might be a need to invoke a future method from the trigger to do certain things asynchronously (for eg., to make a callout, avoid MIXED_DML_OPERATION exception etc.,). In such instances, developers should make sure this invocation is not made if the current context is already asynchronous (ie., either future or batch).
Consider the following scenario. There is a trigger on Account object that invokes a future method as follows,
trigger AccountTrigger on Account (after insert, after update) {
AccountHandler.makeCalloutFutureMethod(Trigger.newMap.keySet());
}
* makeCalloutFutureMethod is a future annotated method
Now, if an Account record is inserted through a batch process or through another future method, the above trigger would throw an exception saying "CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, AccountTrigger: execution of AfterInsert caused by: System.AsyncException: Future method cannot be called from a future or batch method". As the exception message indicates, a future method cannot be invoked from future or batch method execution context.
There are two possible workaround for this problem:
- Update the trigger logic to leverage the System.isFuture() and System.isBatch() calls so that the future method invocation is not made if the current execution context is future or batch. Record created through such cases should be handled separately using a scheduled batch job or something similar. The above example can be updates as follows,
trigger AccountTrigger on Account (after insert, after update) {
if(!System.isFuture() && !System.isBatch())
AccountHandler.makeCalloutFutureMethod(Trigger.newMap.keySet());
}
2.Replace the future method with Queueable Apex. Queueable Apex was introduced in Winter'15 and it is more powerful than future methods.
Please read the following articles to find more information about Queueable Apex:
https://developer.salesforce.com/docs/atlas.enus.apexcode.meta/apexcode/apex_queueing_jobs.htm
https://developer.salesforce.com/blogs/developer-relations/2015/05/queueable-apex-future.html
For more detailed conversations on the topic, feel free to contact us directly or email us at [email protected].
Head of Growth at AirOps
3 年Thank you Andi Giri! This just solved a problem I was having.
Salesforce | Problem Solver | Architect | Consultant | Coveo | IT Leader
4 年Thanks for this article
Good tip!