ApexSensei

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 still Pending
  • after Test.stopTest() → Description is Reviewed
  • a second Contact that was not passed in → stays Pending

Requirements:

  1. Add @future on its own line above the method. Keep it public static void.
  2. Change the first parameter from Contact contact to Id contactId. The checks call completeReview(contactId, reviewResult).
  3. Inside the method, query that one Contact by Id.
  4. Set its Description to reviewResult and 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.

Try this drill free

You write the Apex yourself. ApexSensei runs it and tells you what passed and what did not.

Carry Account work in a Queueable ›