Scheduled Apex
By the end of this lesson, you'll be able to:
- Implement the Schedulable interface
- Schedule a job to run at a recurring time using a cron expression
- Combine Scheduled Apex with Batch Apex for a recurring bulk job
Prerequisites: "Batch Apex"
Implementing Schedulable
public class NightlyAccountCleanupJob implements Schedulable {
public void execute(SchedulableContext context) {
Database.executeBatch(new UpdateStaleAccountsBatch(), 200);
}
}
A Schedulable class's execute method runs automatically at whatever time it's scheduled for — here, kicking off the previous lesson's Batch job, a genuinely common combination: a recurring schedule that processes a large volume of data each time it fires.
Scheduling it with a cron expression
String cronExpression = '0 0 2 * * ?'; // every day at 2:00 AM
System.schedule('Nightly Account Cleanup', cronExpression, new NightlyAccountCleanupJob());
The cron expression (seconds minutes hours day-of-month month day-of-week) defines exactly when the job runs — '0 0 2 * * ?' means "at second 0, minute 0, hour 2, every day" — every night at 2 AM, with no manual trigger required at all.
Why this combination is common
Scheduled Apex alone just runs some code at a set time — it's Batch Apex, called from within it, that actually does meaningful bulk work at scale. This pairing (a nightly schedule kicking off a batch job) is one of the most common real-world Apex patterns: recurring maintenance, data cleanup, or reporting jobs that need to touch a large number of records automatically, on a fixed cadence, with nobody needing to remember to run them manually.
Exercise
Write a cron expression string for "every Monday at 9:00 AM" and the System.schedule call to register it with a class WeeklyReportJob.
Show hint
Day-of-week position uses 2 for Monday in Salesforce's cron syntax (1=Sunday).
Scheduled Apex Quiz
My Notes
Log in to keep private notes on this lesson.
Questions about this lesson
No questions yet — be the first to ask.
Log in to ask a question about this lesson.
Summary
Scheduled Apex runs a job automatically at a specified time — once, or recurring — without anything needing to manually trigger it.