Sub topic 1
Where Scheduled Apex Fits Among Asynchronous Options
Prerequisites
This chapter assumes basic Apex classes, SOQL, DML, and Salesforce governor limits. You should also know how to use Setup or the Developer Console.
Where Scheduled Apex Fits Among Asynchronous Options
Asynchronous Apex runs outside the request that started it. The user does not wait for the work to finish, and the work receives its own transaction.
Choose the tool based on how the work starts:
- Future methods run later and handle small, independent tasks.
- Queueable Apex runs a job that can accept complex state and chain another queueable job.
- Batch Apex processes many records in separate batches.
- Scheduled Apex starts Apex at a defined time or repeated interval.
Scheduled Apex usually coordinates work. The scheduled class should perform a small amount of work or start a batch or queueable job.
Writing a Schedulable Class
A schedulable class implements the Schedulable interface. Salesforce calls its execute method when the schedule fires. The SchedulableContext parameter provides information about the running scheduled job.
This example finds open cases older than seven days and raises their priority:
public class EscalateStaleCases implements Schedulable {
public void execute(SchedulableContext sc) {
List<Case> stale = [
SELECT Id, Priority
FROM Case
WHERE IsClosed = false
AND Priority != 'High'
AND CreatedDate < LAST_N_DAYS:7
LIMIT 200
];
for (Case c : stale) {
c.Priority = 'High';
}
update stale;
}
}The query and update are bulk-safe for the selected records. For a much larger result set, schedule a class that starts Batch Apex instead.
Reading and Writing Cron Expressions
System.schedule uses a cron expression. Salesforce cron expressions have this order:
| Field | Meaning | Example |
|---|---|---|
| Seconds Minutes Hours Day-of-month Month Day-of-week [Year] | When the job runs | `0 0 13 * * ?` |
The following expression runs every day at 1:00 PM:
String cronExp = '0 0 13 * * ?';
Id jobId = System.schedule(
'Escalate stale cases',
cronExp,
new EscalateStaleCases()
);Use ? when you do not specify either the day of month or the day of week. Test schedules with a future date and verify the job in CronTrigger.
Exercise
Which asynchronous Apex tool is the best fit for starting a large cleanup every night?
Show answer
Scheduled Apex should start a Batch Apex job, because Batch Apex processes the records in separate transactions.