Drills › Work in the background
Complete a Contact review in the future
Work in the background · Intermediate · 15 min · Runs in your Salesforce Developer org · Apex Path
Scenario. A support screen saves a Contact review. The screen should respond fast, so the Description update moves to a background job.
Turn a working synchronous method into a @future method that takes an Id, queries the Contact and saves the review later.
What you will learn
A @future method runs later, in its own transaction. It must be static void. Its parameters must be simple values like Id, String and Integer, or lists and sets of them. Records are not allowed, so pass the Id and query the record inside.
@future
public static void refresh(Id accountId) {
}
Gotcha. In a test, future calls run at Test.stopTest(). A transaction can queue up to 50 future calls, and a future method cannot call another one.
The task
Turn the working synchronous method into a @future method, so the review is saved after the caller's transaction ends.
Examples:
completeReview(contactId, 'Reviewed')→ right after the call, Description is stillPending- after
Test.stopTest()→ Description isReviewed - a second Contact that was not passed in → stays
Pending
Requirements:
- Add
@futureon its own line above the method. Keep itpublic static void. - Change the first parameter from
Contact contacttoId contactId. The checks callcompleteReview(contactId, reviewResult). - Inside the method, query that one Contact by Id.
- Set its Description to
reviewResultand update it.
Starter code
public class AS_A43C82691AAA_FutureContactJob {
public static void completeReview(Contact contact, String reviewResult) {
contact.Description = reviewResult;
update contact;
}
}
When it passes
The call is queued as one future call, the Contact stays `Pending` until `Test.stopTest()`, and then only the requested Contact gets the review result.
You write the Apex yourself. ApexSensei runs it and tells you what passed and what did not.