Sub topic 3
Using Future Methods Safely from Triggers
This chapter assumes you know Apex triggers, static methods, SOQL and DML, and governor limits. It covers the trigger pattern, testing, the contexts where future methods are blocked, monitoring, and when to pick another tool.
Calling from a trigger
A trigger can fire for up to 200 records at once. Call the future method once per trigger run with a set of IDs. Calling it once per record can exceed the limit of 50 future calls per transaction.
trigger AccountTrigger on Account (after insert) {
Set<Id> ids = new Set<Id>();
for (Account a : Trigger.new) {
ids.add(a.Id);
}
if (!System.isFuture() && !System.isBatch()) {
AccountService.updateAccountRatings(ids);
}
}The guard matters because a future method that updates accounts can fire this trigger again. Without the guard, that second run would try to call a future method from inside a future method, which Salesforce rejects.
Testing
Queued future methods do not run until the test calls Test.stopTest(). That call runs them synchronously, so you can assert on the results afterward.
@isTest
private class AccountServiceTest {
@isTest
static void futureMethodUpdatesRating() {
Account a = new Account(Name = 'Test Account');
insert a;
Test.startTest();
AccountService.updateAccountRatings(new Set<Id>{ a.Id });
Test.stopTest();
Account result = [SELECT Rating FROM Account WHERE Id = :a.Id];
System.assertEquals('Hot', result.Rating);
}
}Where future methods cannot be called
- From another future method.
- From a Batch Apex
executemethod. - More than 50 times in one transaction.
Check System.isFuture() and System.isBatch() before calling, as the trigger above does.
Monitoring
In Setup, open Apex Jobs. Future calls appear with the job type Future Method, along with their status and any error message. If you need to see a job's progress in more detail, a future method is the wrong tool, because it returns no job ID.
Choosing something else
| Need | Use |
|---|---|
| Simple, short work, primitive parameters | Future method |
| sObjects or custom types as parameters, a job ID, or chained jobs | Queueable Apex |
| Very large data volumes processed in chunks | Batch Apex |
Exercise
A trigger on Account calls a future method inside a for loop, once per record. A data load of 200 accounts fails. Why, and how do you fix it?
Show answer
The loop makes 200 future calls, which exceeds the limit of 50 per transaction. Collect the IDs into a Set<Id> inside the loop and call the future method once after it.