ApexSensei

Drills › Work in the background

Schedule an Account review

Work in the background · Advanced · 22 min · Runs in your Salesforce Developer org · Apex Path

Scenario. A low-priority Account review should run on a known schedule, not while a user waits.

Register a Schedulable class with a cron string, and keep the record work in execute so it runs only when the job fires.

What you will learn

Schedulable Apex runs execute at times set by a cron string. System.schedule(name, cron, job) saves the job and returns its Id. The cron fields are: seconds, minutes, hours, day of month, month, day of week, and an optional year.

System.schedule('Nightly', '0 0 2 * * ?', new NightlyJob());

Gotcha. Day of month and day of week cannot both be set: one must be ?. In a test, the job runs at Test.stopTest(), whatever time the cron says.

The task

Complete the scheduler so schedule registers the job with cron 0 0 0 1 1 ? 2099, and execute later labels only the selected Accounts.

Examples:

  • two selected Ids → both get the label, but only after the job runs
  • one selected Id and one other Account → the other stays Pending
  • empty Id set → the job is still scheduled, and nothing changes

Requirements:

  1. In schedule, call System.schedule with the job name, cron 0 0 0 1 1 ? 2099 and a new instance of this class.
  2. Return the Id that System.schedule gives back.
  3. Do no record work inside schedule. Only execute changes Accounts.
  4. In execute, query the selected Accounts, set Description to the label, and update them once. Do nothing for an empty Id set.

Starter code

public class AS_7F17D42757F6_ScheduledAccountJob implements Schedulable {
    private Set<Id> accountIds;
    private String reviewLabel;

    public AS_7F17D42757F6_ScheduledAccountJob(Set<Id> accountIds, String reviewLabel) {
        this.accountIds = accountIds;
        this.reviewLabel = reviewLabel;
    }

    public void execute(SchedulableContext context) {
    }

    public static Id schedule(Set<Id> accountIds, String reviewLabel, String jobName) {
        return null;
    }
}

When it passes

The job is saved with the right cron, nothing changes until the job runs, then only the selected Accounts get the label. An empty Id set is still scheduled and changes nothing.

Try this drill free

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

‹ Keep counts across Batch transactions · Make a Queueable retry idempotent ›