Sub topic 1
Why Run Code Asynchronously
Prerequisites
This chapter assumes you know basic Apex syntax (classes, static methods, collections), SOQL and DML, and Apex triggers. It also assumes you know that Salesforce enforces governor limits.
Why run code asynchronously
Synchronous Apex runs inside the user's request. The user waits, and the work shares one set of governor limits. Some work does not fit there: callouts to external systems, slow processing, and DML on setup objects that conflicts with other DML. Asynchronous Apex moves that work into a separate transaction that starts after the current one finishes.
Declaring and calling a future method
A future method has the @future annotation. It must be static and return void. You call it like any static method, but Salesforce queues it instead of running it immediately.
public class AccountService {
@future
public static void updateAccountRatings(Set<Id> accountIds) {
List<Account> accounts = [SELECT Id, Rating FROM Account WHERE Id IN :accountIds];
for (Account a : accounts) {
a.Rating = 'Hot';
}
update accounts;
}
}What a future method can accept
Parameters must be primitive types, arrays of primitives, or collections of primitives. This means you can pass Id, String, Integer, Set<Id>, or List<String>. You cannot pass an sObject or a custom class instance. The method cannot return a value.
Passing record IDs and re-querying data
The method may run seconds or minutes after you call it. A record you passed in could change before then. So pass IDs, not field values, and query the records inside the method. The example above does this. It reads the current Rating data instead of using a stale copy.
Exercise
Why can a future method not take a List<Account> as a parameter, and what should you pass instead?
Show answer
Future methods accept only primitives and collections of primitives, and the data could change before the method runs. Pass a Set<Id> of the account IDs and re-query the accounts inside the method.