Sub topic 4
Scheduling a Job with System.schedule
This chapter assumes you can write a Schedulable class, read a basic cron expression, and run Anonymous Apex from the Developer Console. It covers the call that registers a job, what it returns, and the errors and limits you will meet when you use it.
What System.schedule does
System.schedule registers a Schedulable class to run on a timetable. It takes three arguments and returns one value.
| Argument | Type | Purpose |
|---|---|---|
| `jobName` | `String` | A label for the job. Use it later to find the job. |
| `cronExp` | `String` | The cron expression that defines when the job runs. |
| `schedulable` | `Schedulable` | An instance of your class that implements `Schedulable`. |
The return value is the Id of the new CronTrigger record. That record represents the schedule. It is not the same thing as a single run of the job.
// Seconds Minutes Hours Day_of_month Month Day_of_week [Year]
String cronExp = '0 0 13 * * ?'; // every day at 1:00 PM
Id jobId = System.schedule('Escalate stale cases', cronExp, new EscalateStaleCases());
System.debug('Scheduled with CronTrigger Id ' + jobId);Run this in Anonymous Apex and the job is registered immediately. Nothing runs at that moment. The platform waits for the next matching time and then calls execute on your instance.
The call only creates a schedule. It does not run your class, so any error inside execute appears later, at run time.
Choosing a cron expression
The expression has six required fields and one optional field:
- Seconds
- Minutes
- Hours
- Day of month
- Month
- Day of week
- Year (optional)
Day of month and day of week cannot both hold a value. Put ? in one of them. Here are some common timetables.
| Expression | Meaning |
|---|---|
| `0 0 13 * * ?` | Every day at 1:00 PM |
| `0 30 6 ? * MON-FRI` | Weekdays at 6:30 AM |
| `0 0 2 1 * ?` | The first day of every month at 2:00 AM |
| `0 0 0/4 * * ?` | Every four hours, starting at midnight |
| `0 0 0 15 3 ? 2099` | Once, on 15 March 2099 |
The platform interprets the time in the time zone of the user who schedules the job. If you schedule the same expression from an org with a different user time zone, the real run time shifts. When a job must run at a specific wall-clock time, check the time zone of the user who schedules it.
The Setup UI offers fewer timetables than cron does. It cannot express "every four hours", for example. System.schedule is the way to get those.
Scheduling several times a day
The cron seconds and minutes fields let you run a job at several minutes within an hour. Each System.schedule call, however, creates one CronTrigger, and the Setup UI is no more flexible. If you need a pattern that one expression cannot describe, register several jobs. Each one needs its own name.
// Run at :00 and :30 past every hour: one expression covers it.
System.schedule('Escalate stale cases twice hourly', '0 0,30 * * * ?', new EscalateStaleCases());
// Run at 8:15, 12:15 and 17:15 only: one expression also covers it.
System.schedule('Escalate stale cases workday', '0 15 8,12,17 * * ?', new EscalateStaleCases());If you do need separate jobs, give each a distinct name. This loop is the usual pattern:
List<Integer> minutes = new List<Integer>{ 0, 15, 30, 45 };
for (Integer m : minutes) {
String name = 'Escalate stale cases :' + String.valueOf(m).leftPad(2, '0');
String cron = '0 ' + m + ' * * * ?';
System.schedule(name, cron, new EscalateStaleCases());
}This uses four of the 100 scheduled job slots in the org. Prefer one expression such as 0 0/15 * * * ? where you can, because that uses one slot.
Job names must be unique
Salesforce rejects a second job with the same name as one that is still scheduled. The error reads like The Apex job named "Escalate stale cases" is already scheduled for execution. This causes the most common failure with System.schedule. A deployment script, a post-install handler or a setup routine runs twice, and the second run throws.
A helper that is safe to call repeatedly aborts any existing job of that name, then schedules a fresh one.
public class EscalateStaleCasesScheduler {
public static final String JOB_NAME = 'Escalate stale cases';
public static final String CRON = '0 0 13 * * ?';
public static Id scheduleOrReplace() {
for (CronTrigger ct : [
SELECT Id
FROM CronTrigger
WHERE CronJobDetail.Name = :JOB_NAME
AND CronJobDetail.JobType = '7'
]) {
System.abortJob(ct.Id);
}
return System.schedule(JOB_NAME, CRON, new EscalateStaleCases());
}
}JobType = '7' limits the query to Scheduled Apex jobs. Other job types share the same object. Calling EscalateStaleCasesScheduler.scheduleOrReplace() from Anonymous Apex now gives the same result whether the job exists or not.
What the platform checks
System.schedule validates its input before it stores anything.
- Invalid syntax. A malformed expression, such as one with too few fields or both day fields set, throws an exception instead of creating a job.
- No future fire time. An expression that can never fire again, for example
0 0 0 1 1 ? 2000, throws aSystem.AsyncException. The message says the trigger will never fire. - Duplicate name. Covered above.
- Job limit. An org can hold at most 100 scheduled Apex jobs at one time. Scheduling the 101st throws an exception.
Because these are exceptions at the call site, you can catch them where you need to.
try {
System.schedule('Escalate stale cases', '0 0 0 1 1 ? 2000', new EscalateStaleCases());
} catch (Exception e) {
System.debug(e.getTypeName() + ': ' + e.getMessage());
}Catch Exception here and log the type name. The exact exception type depends on which check failed.
State and who runs the job
You pass an instance of the class, not a class name. The platform serializes that instance when you call System.schedule and restores it each time the job fires. Anything you put in member variables at schedule time is available in execute.
public class EscalateByAge implements Schedulable {
private Integer ageInDays;
public EscalateByAge(Integer ageInDays) {
this.ageInDays = ageInDays;
}
public void execute(SchedulableContext sc) {
Date cutoff = Date.today().addDays(-ageInDays);
List<Case> stale = [
SELECT Id
FROM Case
WHERE IsClosed = false
AND Priority != 'High'
AND CreatedDate < :cutoff
LIMIT 200
];
for (Case c : stale) {
c.Priority = 'High';
}
update stale;
}
}Schedule it with System.schedule('Escalate 14 day cases', '0 0 6 * * ?', new EscalateByAge(14));. The value 14 is stored with the job. To change it, abort the job and schedule a new instance.
Keep these points in mind:
- Member variables must be serializable. Do not store a
Database.QueryLocatoror similar non-serializable objects. Store Ids, strings, numbers and other simple values. - Do not rely on
staticvariables to carry values between runs. Each run starts with fresh static state. - Fields marked
transientare not restored. - The job runs as the user who scheduled it. If that user is deactivated or loses access to the objects or fields the job touches, runs can fail. For a job meant to last, schedule it as an integration or admin user whose account will not change.
Timing is approximate
The platform guarantees that a job starts at or after the scheduled time, not at exactly that time. When the system is busy, the job waits in a queue. Do not write logic that requires a run at a precise second. Design execute so that a late run gives the same result as an on-time run. Querying "cases older than seven days" is an example of that kind of logic. Querying "cases created in the last 60 minutes" is not, because a late or skipped run loses records.
Where to call System.schedule
The common places are Anonymous Apex, a deployment or post-install script, and a setup method that an admin runs once. Avoid calling it from a trigger. A trigger can fire many times, which risks duplicate names and quickly fills the 100-job limit.
If a scheduled job must run again at a computed time, one pattern is to schedule the next run from inside execute, using System.schedule with a new name and a new expression. This creates job records quickly and the old ones need cleanup. For a fixed timetable, use one cron expression instead.
Common errors at a glance
| Symptom | Likely cause | Fix |
|---|---|---|
| "already scheduled for execution" | A job with that name exists | Abort the old job first, or use a different name |
| "will never fire" | Year or date in the expression is in the past | Use a future date, or remove the year |
| Invalid expression exception | Wrong field count, or `?` missing from a day field | Check all six fields and put `?` in one day field |
| Limit exception on schedule | 100 scheduled jobs already exist | Abort unused jobs or combine them |
| Job runs at the wrong hour | User time zone differs from your assumption | Check the scheduling user's time zone |
| Job fails after a user leaves | The scheduling user lost access | Reschedule under a stable user |
Practice
Exercise
A deployment script calls System.schedule('Nightly cleanup', '0 0 2 ?', new NightlyTaskCleanup()). The script runs successfully the first time and throws on the second run in the same org. What causes the error, and how do you make the script safe to run repeatedly?
Show answer
The first run created a scheduled job named 'Nightly cleanup', and Salesforce does not allow a second job with a name that is still scheduled. To make the script repeatable, query CronTrigger for CronJobDetail.Name = 'Nightly cleanup' (and CronJobDetail.JobType = '7'), call System.abortJob on each match, and then call System.schedule.
Exercise
Write one cron expression that runs a job every 15 minutes, every day. Then say how many of the org's scheduled job slots it uses compared with scheduling four separate jobs at minutes 0, 15, 30 and 45.
Show answer
'0 0/15 * ?' runs at minutes 0, 15, 30 and 45 of every hour. It uses one slot, because it creates one CronTrigger. Four separate jobs use four of the 100 available slots and each needs a unique name.
Exercise
You schedule new EscalateByAge(14) and later need the threshold to be 30 days. Why can't you just change a field in the class, and what do you do instead?
Show answer
The platform serialized the instance with ageInDays = 14 when you called System.schedule, and it restores that stored state at each run. The running job does not pick up a new value. Abort the existing CronTrigger with System.abortJob and schedule a new EscalateByAge(30) instance.