Sub topic 4
Scheduling a Job with System.schedule
This chapter covers how to create a scheduled job from code. It assumes you can write a Schedulable class, read a cron expression, and run Apex in the Developer Console. Cron syntax is covered in the previous chapter, so here it is only applied.
What System.schedule does
System.schedule registers a Schedulable class to run on a cron timetable. It takes three arguments:
- A job name. Salesforce shows this name in Setup and stores it on the job's
CronJobDetailrecord. - A cron expression, as a string.
- An instance of a class that implements
Schedulable.
It returns the ID of the new CronTrigger record. That record describes the job and tracks its state, and a later chapter uses it for monitoring and aborting.
// 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());The class passed in is the one from the earlier chapter:
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;
}
}After the call returns, the job exists. You do not need to keep the instance or the ID for the job to keep running.
How a scheduling call flows
The call creates records. Salesforce then starts the job from those records at the times the expression gives.
Where to call it
You can run the call in anonymous Apex from the Developer Console. This is common for a one-off setup in each org:
System.schedule('Escalate stale cases', '0 0 13 * * ?', new EscalateStaleCases());A common alternative is to put the call in a static method on the Schedulable class. That keeps the name and the cron expression next to the code they belong to, so every org gets the same timetable.
public class EscalateStaleCases implements Schedulable {
public static final String JOB_NAME = 'Escalate stale cases';
public static final String CRON = '0 0 13 * * ?';
public static Id start() {
return System.schedule(JOB_NAME, CRON, new EscalateStaleCases());
}
public void execute(SchedulableContext sc) {
// job logic goes here
}
}Run EscalateStaleCases.start(); once from anonymous Apex. Running it twice is the first common error, covered below.
Common cron patterns
The expression has the fields seconds, minutes, hours, day of month, month, day of week, and an optional year. Either day of month or day of week must be ?.
| 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 each month at 2:00 AM |
| `0 0 0 15 3 ? 2099` | One time only, on 15 March 2099 |
The job runs in the time zone of the user who scheduled it. A job set for 1:00 PM by a user in one zone fires at a different clock time than the same job scheduled by a user in another zone.
Common errors
Duplicate job names. Job names do not have to be unique in every case, but two jobs with the same name make monitoring confusing. Running start() twice leaves two copies of the job, and each one runs. Query CronTrigger by name before you schedule, or abort the old job first.
Scheduling from a trigger or from inside the job. Calling System.schedule in a trigger is allowed, but it is risky. A trigger can fire many times in one transaction, and each call adds another job. Salesforce also caps the number of scheduled jobs, so a runaway loop can use up the cap. Schedule from setup code, not from record events.
Expecting an exact start. The cron expression sets the earliest time the job may start. If the org is busy, the job can start a little later.
An expression that never fires. If the expression has no future fire time, for example a year in the past, System.schedule throws an exception when you call it. A bad format, such as using * in both day fields, also throws an exception, and no job is created.
Doing too much in execute. The scheduled class runs under normal synchronous governor limits. Keep the work small, or start a batch job from execute. That is the subject of a later chapter.
Checking the result
The returned ID is a CronTrigger ID, so you can read the job straight away:
Id jobId = System.schedule('Escalate stale cases', '0 0 13 * * ?', new EscalateStaleCases());
CronTrigger ct = [
SELECT CronExpression, State, NextFireTime
FROM CronTrigger
WHERE Id = :jobId
];
System.debug(ct.State + ' next run: ' + ct.NextFireTime);A job that has not run yet has the state WAITING. NextFireTime shows when it will first run.
Exercise
You run EscalateStaleCases.start(); twice by mistake in the same org. What happens, and how can you avoid it in the start method?
Show answer
Two jobs with the same name and timetable are created, so the class runs twice at each fire time. To avoid it, query CronTrigger for a job with the same CronJobDetail.Name before calling System.schedule, and abort the existing job or skip scheduling if one is found.
Exercise
Write the cron expression for a job that runs at 6:30 AM on weekdays, and say what the ? stands for.
Show answer
0 30 6 ? * MON-FRI. The ? means "no specific value" in the day of month field, which is required because the day of week field already sets the days.