Sub topic 9
Scheduled Apex: running code on a schedule
Scheduled Apex runs a class at times you define, such as every night at 02:00 or on the first day of each month. This chapter assumes you know basic Apex syntax, SOQL and DML, governor limits at a high level, and how to write a simple unit test. It covers the Schedulable interface, cron expressions, the limits on scheduled jobs, and how to test and manage them.
What Scheduled Apex is for
The other tools in this tutorial run work because something happened: a trigger fired, a user clicked a button, or another job finished. Scheduled Apex runs work because the clock says so. Typical uses are:
- Nightly cleanup of stale records.
- Weekly digest emails or reports.
- Periodic synchronization with an external system.
- Starting a Batch Apex job at a quiet time of day.
A scheduled class does not do heavy lifting well by itself. It runs in a normal asynchronous transaction with the usual asynchronous governor limits. If the work touches many records, the scheduled class should start a Batch or Queueable job and return quickly. The "Combining the tools" chapter covers that pattern in detail. This chapter shows the basic form.
The Schedulable interface
A scheduled class implements Schedulable. The interface has one method, execute, which receives a SchedulableContext.
public class NightlyStaleLeadJob implements Schedulable {
public void execute(SchedulableContext sc) {
Database.executeBatch(new StaleLeadBatch(), 200);
}
}The SchedulableContext gives you one useful thing: sc.getTriggerId(), which returns the Id of the CronTrigger record for this schedule. You can use it to look up the schedule's status or to abort it.
The class must be global or public. In a managed package, it must be global.
Keep execute short. In this example the class only starts a batch job. The query, the record updates, and the large-volume handling all live in the batch class.
Scheduling a job
You schedule a class in code or in the Setup UI.
Scheduling in code with System.schedule
System.schedule takes three arguments: a job name, a cron expression, and an instance of your class. It returns the Id of the CronTrigger.
// 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 job name must be unique among scheduled jobs. If you call System.schedule twice with the same name, the second call throws an exception. This matters when you put the call in code that can run more than once, such as a deployment script.
Scheduling in the Setup UI
In Setup, search for Apex Classes and click Schedule Apex. You pick the class, a name, a frequency (daily, weekly, or monthly), a date range, and a preferred start time. The UI is simpler than cron but less flexible. For example, it cannot express "every 15 minutes".
Cron expressions
Apex cron expressions have six required fields and one optional field, separated by spaces.
| Field | Allowed values | Notes |
|---|---|---|
| Seconds | 0-59 | |
| Minutes | 0-59 | |
| Hours | 0-23 | 24-hour clock |
| Day of month | 1-31 | |
| Month | 1-12 or JAN-DEC | |
| Day of week | 1-7 or SUN-SAT | 1 is Sunday |
| Year (optional) | 1970-2099 |
The special characters are:
| Character | Meaning |
|---|---|
| `*` | Every value in the field |
| `?` | No specific value. Allowed only in day of month and day of week. |
| `,` | A list of values, such as `MON,WED,FRI` |
| `-` | A range, such as `9-17` |
| `/` | An increment, such as `0/15` means every 15 starting at 0 |
| `L` | The last day of the month, or the last given weekday |
| `W` | The nearest weekday to a given day of the month |
| `#` | The nth weekday of the month, such as `6#3` means the third Friday |
Day of month and day of week cannot both have a specific value. One of them must be ?. This is the most common cause of an invalid cron expression.
Some examples:
| Expression | Runs |
|---|---|
| `0 0 2 * * ?` | Every day at 02:00 |
| `0 30 8 ? * MON-FRI` | Weekdays at 08:30 |
| `0 0 0 1 * ?` | Midnight on the first day of every month |
| `0 0 12 L * ?` | Noon on the last day of every month |
| `0 0 9 ? * 6#1` | 09:00 on the first Friday of every month |
The time zone is the time zone of the user who schedules the job. If a user in one time zone creates the schedule and the org later changes hands, the job keeps running in the original user's time zone. Check this when a job seems to fire an hour off, especially around daylight saving changes.
Running more often than hourly
You can express minutes with a cron expression, for example 0 0/15 * * * ? for every 15 minutes. Some documentation and older advice say the minimum interval is one hour, because the Setup UI only offers hourly or longer choices. The cron expression accepts finer intervals. A common alternative is to schedule several jobs with different minute values:
System.schedule('Sync at :00', '0 0 * * * ?', new PartnerSyncSchedule());
System.schedule('Sync at :15', '0 15 * * * ?', new PartnerSyncSchedule());
System.schedule('Sync at :30', '0 30 * * * ?', new PartnerSyncSchedule());
System.schedule('Sync at :45', '0 45 * * * ?', new PartnerSyncSchedule());Each of these uses one of your scheduled job slots (see the limits below), so the single 0/15 expression is cheaper when it works.
Limits and behavior to know
- 100 scheduled jobs. An org can have at most 100 scheduled Apex jobs at one time. Each call to
System.schedulethat has not yet expired or been deleted counts toward this. - Execution is not exact. The job starts at or after the scheduled time, when system resources are available. A job set for 02:00 may start a little later. Do not rely on a start time to the second.
- Asynchronous limits apply. The
executemethod gets the asynchronous governor limits, for example 200 SOQL queries and a 60-second CPU limit. - No callouts directly from Schedulable. A
Schedulableclass cannot make a callout in its ownexecutemethod. To call an external service, hand the work to a@future(callout=true)method, a Queueable class that implementsDatabase.AllowsCallouts, or a batch class that implementsDatabase.AllowsCallouts. - Starting other async jobs counts. A scheduled execution can start batch jobs, but the org-wide limit of 5 queued or active batch jobs still applies. If the batch queue is full, a call to
Database.executeBatchfrom the scheduler is placed in the Apex Flex Queue, where it waits in a holding status. - Class edits and schedules. You cannot save changes to a class, or to a class it depends on, while a scheduled instance of that class is waiting to run. In practice, deployments can fail with an error saying the class has pending scheduled jobs. Abort the schedule first, deploy, and schedule again.
Scheduling from inside a job
A common pattern is for a scheduled class to be its own scheduler. After it runs, it schedules the next run at a computed time. This is how people get intervals that cron cannot express.
public class RetryScheduler implements Schedulable {
public void execute(SchedulableContext sc) {
// Do or start the work here.
Database.executeBatch(new StaleLeadBatch(), 200);
// Remove this run's CronTrigger so the slot is freed.
System.abortJob(sc.getTriggerId());
// Schedule the next run in 10 minutes.
Datetime next = Datetime.now().addMinutes(10);
String cron = next.format('s m H d M \'?\' yyyy');
System.schedule('Retry ' + next.getTime(), cron, new RetryScheduler());
}
}Two details make this work. The job name includes a timestamp, so each name is unique. The call to System.abortJob removes the finished trigger so scheduled slots do not pile up toward the limit of 100. If the class throws before it reschedules, the chain stops and nobody is told. Use this pattern carefully and monitor it.
Monitoring and managing scheduled jobs
Scheduled jobs appear in two places.
- Setup, Scheduled Jobs. This page lists each scheduled job with its name, submitter, next run time, and a Del link to delete it.
- The
CronTriggerobject. You can query it in code.
List<CronTrigger> jobs = [
SELECT Id, CronJobDetail.Name, CronExpression, State, NextFireTime, PreviousFireTime
FROM CronTrigger
WHERE CronJobDetail.JobType = '7'
];
for (CronTrigger ct : jobs) {
System.debug(ct.CronJobDetail.Name + ' next runs ' + ct.NextFireTime);
}JobType = '7' selects scheduled Apex. The State field shows WAITING for a job that will run again, EXECUTING while it runs, and COMPLETE or DELETED when it is finished.
To remove a schedule, pass the CronTrigger Id to System.abortJob:
System.abortJob(cronId);The work that a scheduled class starts shows up separately. A batch job started by the scheduler appears in Apex Jobs and in AsyncApexJob under its own Id. The scheduled run itself also appears in AsyncApexJob with JobType = 'ScheduledApex'.
Testing Scheduled Apex
A scheduled class is tested by scheduling it between Test.startTest and Test.stopTest. The job runs when Test.stopTest is called, whatever its cron expression says. The cron expression in a test should still be valid and in the future.
@IsTest
private class NightlyStaleLeadJobTest {
@IsTest
static void schedulesAndRunsBatch() {
Lead l = new Lead(LastName = 'Old', Company = 'Acme');
insert l;
Test.setCreatedDate(l.Id, Datetime.now().addDays(-400));
// A far-future date keeps the cron expression valid.
String cron = '0 0 2 1 1 ? 2099';
Test.startTest();
Id cronId = System.schedule('Test stale lead job', cron, new NightlyStaleLeadJob());
CronTrigger before = [
SELECT State, TimesTriggered FROM CronTrigger WHERE Id = :cronId
];
Assert.areEqual(0, before.TimesTriggered);
Test.stopTest();
CronTrigger after = [
SELECT State, TimesTriggered FROM CronTrigger WHERE Id = :cronId
];
Assert.areEqual(1, after.TimesTriggered);
}
}In a test, Test.stopTest also finishes any batch job that the scheduled class started, as long as the query returns few enough records for one batch. Assert on both the CronTrigger and the data the batch changed. Test the batch logic in its own test class, and keep the scheduler test small. The scheduler test only needs to prove that the schedule is accepted and that the class starts the right job.
Note that LastModifiedDate cannot be set directly in a test, which is why the example uses Test.setCreatedDate as an illustration of controlling record dates. If your batch filters on LastModifiedDate, either relax the query for tests with a flag, or run the test against SystemModstamp and CreatedDate-based logic that you can control.
Common errors
| Symptom | Likely cause |
|---|---|
| `System.StringException: Invalid cron expression` or a similar message | Both day of month and day of week are set, or a field has a value out of range |
| `Another scheduled job exists with this name` style error | The job name is not unique |
| Deployment fails with a message about pending scheduled jobs | A schedule exists for the class being changed |
| A scheduled job never starts a batch | The batch queue is full, so the job is held in the Flex Queue |
| Job fires an hour off | The schedule uses the creating user's time zone, and daylight saving applies |
| `Callout from scheduled Apex not supported` | The `execute` method makes a callout directly |
Decision notes
Choose Scheduled Apex when the trigger for the work is the calendar. Do not use it for work that should happen right after a record changes. Use a trigger with a Queueable or future method for that. Do not use a tight schedule to poll for changes if an event-driven design is available, because every scheduled run uses a slot and system resources.
Exercise
Write a cron expression that runs a job at 06:45 on every weekday (Monday to Friday), and explain why one of the day fields must be ?.
Show answer
Use 0 45 6 ? * MON-FRI. Apex does not let you give a specific value to both day of month and day of week, because the two could conflict. Here the weekday restriction is in the day of week field, so day of month is set to ? to mean "no specific value".
Exercise
A scheduled class must send data to an external service every night. Its execute method makes the HTTP callout directly and fails. What are two ways to fix it?
Show answer
Move the callout out of execute. One option is to call a @future(callout=true) method from execute. The other is to enqueue a Queueable class that implements Database.AllowsCallouts, or to start a batch class that implements Database.AllowsCallouts.