Sub topic 2
When a Future Method Runs and in What Order
This chapter assumes you know Apex classes, SOQL, DML, and basic governor limits.
When a future method runs and in what order
Calling a future method does not run it. Salesforce queues the request. The queued job starts only after the current transaction commits, when system resources are free. Two consequences follow:
- Code after the call keeps running first.
- Order between future calls is not guaranteed, so never assume one finishes before another.
Making callouts with callout=true
A future method cannot make a callout unless you set callout=true. This lets you call external services from a trigger, where callouts are not allowed directly.
public class BillingCallout {
@future(callout=true)
public static void sendAccounts(Set<Id> accountIds) {
List<Account> accounts = [SELECT Id, Name FROM Account WHERE Id IN :accountIds];
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Billing_API/accounts');
req.setMethod('POST');
req.setHeader('Content-Type', 'application/json');
req.setBody(JSON.serialize(accounts));
HttpResponse res = new Http().send(req);
if (res.getStatusCode() != 200) {
System.debug(LoggingLevel.ERROR, 'Callout failed: ' + res.getStatus());
}
}
}Billing_API is a placeholder Named Credential that you must define.
Fixing mixed DML errors
Salesforce blocks DML on setup objects (such as UserRole) and non-setup objects (such as Account) in one transaction. A future method gets its own transaction, so it avoids the error.
public class SetupDmlHelper {
@future
public static void createRole(String roleName, String developerName) {
insert new UserRole(Name = roleName, DeveloperName = developerName);
}
}Governor limits that apply
| Limit | Value |
|---|---|
| Future calls per Apex invocation | 50 |
| Future calls per 24 hours | 250,000, or licenses × 200 if higher |
| Limits inside the future method | Asynchronous limits, which are higher than synchronous ones |
Exercise
A trigger inserts an Account, then calls a future method that inserts a UserRole. Why does this avoid a mixed DML error, and can you rely on the role existing on the next line of the trigger?
Show answer
The future method runs in a separate transaction, so the setup and non-setup DML are not combined. You cannot rely on the role existing on the next line, because the future method runs only after the current transaction commits.