Sub topic 9
Scheduled Apex: running code on a schedule
This chapter assumes you can write basic Apex classes, run SOQL and DML, and know what a governor limit is. You should also have read the earlier chapters on Queueable and Batch Apex.
What Scheduled Apex does
Scheduled Apex runs a class at a time you choose, once or on a repeating schedule. The class implements the Schedulable interface. Salesforce starts it for you, so no user action or record change is needed.
A scheduled job does not process data in a special way. It is a timer that starts ordinary Apex. Its execute method runs in a normal transaction with the usual synchronous governor limits, so heavy work should be handed to a Batch or Queueable job.
Writing a Schedulable class
The interface has one method, execute(SchedulableContext sc). Keep it short and delegate the real work.
public class NightlyStaleLeadJob implements Schedulable {
public void execute(SchedulableContext sc) {
Database.executeBatch(new StaleLeadBatch(), 200);
}
}This class starts the StaleLeadBatch job with a scope of 200 records. The scheduler only decides when the work begins.
Scheduling with a cron expression
You schedule the class with System.schedule. It takes a job name, a cron expression, and an instance of your class. It returns the Id of the CronTrigger record.
// Seconds Minutes Hours Day_of_month Month Day_of_week
String cron = '0 0 2 * * ?';
Id cronId = System.schedule('Nightly stale lead cleanup', cron, new NightlyStaleLeadJob());The expression 0 0 2 * * ? runs every day at 02:00. The job name must be unique among scheduled jobs, so scheduling the same name twice fails.
| Field | Position | Allowed values |
|---|---|---|
| Seconds | 1 | 0-59 |
| Minutes | 2 | 0-59 |
| Hours | 3 | 0-23 |
| Day of month | 4 | 1-31, or `*`, `?`, `L` |
| Month | 5 | 1-12, or `JAN`-`DEC` |
| Day of week | 6 | 1-7, or `SUN`-`SAT` |
An optional seventh field holds the year. Use ? in either the day-of-month or day-of-week field, because you can only constrain one of them.
Some common expressions:
0 0 2 * * ?runs every day at 02:00.0 30 8 ? * MON-FRIruns at 08:30 on weekdays.0 0 0 1 * ?runs at midnight on the first day of each month.
The time uses the time zone of the user who schedules the job.
How a scheduled run flows
Limits to know
- An org can have at most 100 scheduled Apex jobs at one time. Check the current figure in the Salesforce limits documentation.
executeruns under the synchronous limits, such as 100 SOQL queries and 150 DML statements, so avoid doing the data work there.- A scheduled run does not start twice at once for the same job, but a long-running batch it launched can still be running when the next run starts. Plan for overlap if your batch takes longer than the interval.
- Scheduled jobs run as the user who scheduled them. If that user is deactivated, review who owns the job.
Rescheduling and removing jobs
Scheduled jobs stay in place until they finish or you delete them. To remove one, pass its CronTrigger Id to System.abortJob.
CronTrigger ct = [
SELECT Id FROM CronTrigger
WHERE CronJobDetail.Name = 'Nightly stale lead cleanup'
LIMIT 1
];
System.abortJob(ct.Id);Abort first, then schedule again, when you want to change the time. Otherwise the unique-name rule rejects the new job.
Common mistakes
- Putting queries and updates for thousands of records directly in
execute. Use a batch job instead. - Using
*in both day fields. One of them must be?. - Reusing a job name when rescheduling.
- Assuming the job runs at the exact second. Salesforce queues scheduled jobs, so the start can be delayed when the system is busy.
Exercise
Write the cron expression that runs a job at 06:15 every Monday, and explain why the scheduled class should usually call Database.executeBatch instead of updating records itself.
Show answer
The expression is 0 15 6 ? * MON. The execute method of a Schedulable class runs in a single transaction with synchronous governor limits, so updating many records there can hit those limits. Database.executeBatch splits the work into separate transactions, each with its own limits.