Sub topic 3
Reading and writing cron expressions
This chapter assumes you can write a basic Apex class and call System.schedule, which the previous chapters introduced. Here you learn to read a cron expression field by field, write the ones you need, and avoid the mistakes that make a job fire at the wrong time or fail to schedule.
What a cron expression is
A cron expression is a string that describes a timetable. System.schedule takes one as its second argument, and Salesforce stores it on the job's CronTrigger record. Apex uses a Quartz-style format. It has six required fields and one optional field, separated by spaces:
Seconds Minutes Hours Day_of_month Month Day_of_week [Year]The expression 0 0 13 * * ? reads as follows:
- Seconds is
0. - Minutes is
0. - Hours is
13, which is 1 PM on a 24-hour clock. - Day of month is
*, so every day. - Month is
*, so every month. - Day of week is
?, meaning no specific value.
The job therefore runs every day at 13:00:00.
Field values
| Field | Allowed values | Notes |
|---|---|---|
| Seconds | 0-59 | Start time is not exact. See the callout below. |
| Minutes | 0-59 | |
| Hours | 0-23 | 24-hour clock. |
| Day of month | 1-31 | Must be compatible with the month. |
| Month | 1-12 or JAN-DEC | 1 is January. |
| Day of week | 1-7 or SUN-SAT | 1 is Sunday, 7 is Saturday. |
| Year | blank or 1970-2099 | Optional. |
Special characters
Each field accepts a few operators in addition to plain numbers.
| Character | Meaning | Example | Result |
|---|---|---|---|
| `*` | Every value in the field | `*` in Month | Every month |
| `?` | No specific value. Only in day of month and day of week | `?` in Day_of_week | Day of week is ignored |
| `-` | Range | `MON-FRI` | Monday to Friday |
| `,` | List of values | `1,4,7,10` in Month | January, April, July, October |
| `/` | Increment: `start/step` | `0/15` in Minutes | Minutes 0, 15, 30, 45 |
| `L` | Last | `L` in Day_of_month | Last day of the month |
| `W` | Nearest weekday | `15W` in Day_of_month | Weekday closest to the 15th |
| `#` | Nth weekday of the month | `MON#2` in Day_of_week | Second Monday |
The `?` rule
The day-of-month and day-of-week fields overlap. Both can pick days, so they can contradict each other: "the 15th" and "every Monday" describe different days. To avoid this, you must put ? in one of the two fields and a real value in the other.
- To run on a date, put the date in Dayofmonth and
?in Dayofweek:0 0 0 1 * ?. - To run on a weekday, put
?in Dayofmonth and the weekday in Dayofweek:0 30 6 ? * MON-FRI.
Using * in both fields, or a value in both, makes System.schedule throw an exception. If you want "every day", use * ? in the last two required positions, as in 0 0 13 * * ?.
Increments with `/`
The value before the slash is the starting point and the value after it is the step. 0/15 in minutes gives 0, 15, 30 and 45. 5/20 gives 5, 25 and 45. The sequence stops at the end of the field's range and does not wrap into the next hour. The next hour starts the sequence again from the start value.
That last point matters for steps that do not divide the range evenly. 0/25 in minutes fires at :00, :25 and :50, then at :00 again in the next hour, so the gap between :50 and :00 is only 10 minutes.
`L`, `W` and `#`
Lin Dayofmonth means the last day of the month, whether that is the 28th, 29th, 30th or 31st. This is the safe way to say "month end".Lin Dayofweek on its own means Saturday. With a number before it,6Lmeans the last Friday of the month.15Wmeans the weekday nearest the 15th. If the 15th is a Saturday, the job runs on Friday the 14th. If it is a Sunday, it runs on Monday the 16th. The nearest weekday never crosses into another month.1Won a Saturday the 1st runs on Monday the 3rd.LWmeans the last weekday of the month.2#1orMON#1means the first Monday of the month, where the number after#is which occurrence.
Avoid combining L or W with lists or ranges in the same field. Keep each of them as the only value in its field.
Worked examples
| Goal | Expression |
|---|---|
| Every day at 1:00 PM | `0 0 13 * * ?` |
| Weekdays at 6:30 AM | `0 30 6 ? * MON-FRI` |
| Every 15 minutes | `0 0/15 * * * ?` |
| Every hour on the hour | `0 0 * * * ?` |
| Midnight on the 1st of each month | `0 0 0 1 * ?` |
| 11:00 PM on the last day of each month | `0 0 23 L * ?` |
| 8:00 AM on the weekday nearest the 15th | `0 0 8 15W * ?` |
| 9:00 AM on the first Monday of each month | `0 0 9 ? * MON#1` |
| 5:00 PM on the last Friday of each month | `0 0 17 ? * 6L` |
| 2:00 AM on the 1st of each quarter | `0 0 2 1 1,4,7,10 ?` |
| Once, at midnight on 15 March 2099 | `0 0 0 15 3 ? 2099` |
To read an unfamiliar expression, go field by field from left to right and say each one aloud. Then check that exactly one of the last two day fields is ?.
A common mistake is to write 0 15 * * * ? for "every 15 minutes". Here the 15 sits in the minutes field as a single value, so the job runs once an hour at :15. The 0/15 form is the one that repeats.
Time zones and daylight saving
Salesforce interprets the hours field in the time zone of the user who schedules the job. Whoever calls System.schedule or uses the Setup page decides the zone, and the expression itself contains no zone information. A job scheduled by an admin in New York for 0 0 13 * * ? runs at 1 PM New York time, even if the org's default time zone is different.
Two consequences follow:
- If the user who created the job later changes time zone, check the next run time on the
CronTriggerrecord. - Around a daylight saving change, a local time that does not exist (for example 02:30 on the day clocks move forward) is a risk. Avoid placing jobs between 01:00 and 03:00 if the exact run matters. Verify behavior in a sandbox if you must.
The optional year and expressions that never fire
The year field lets you schedule a one-time run. It also makes a mistake possible. If the expression describes a moment that has already passed, there is nothing left to schedule, and System.schedule throws an exception whose message says the trigger will never fire. This is why the test examples in this tutorial use a year far in the future, such as 2099. That keeps the job from ever running during the test while still producing a valid CronTrigger.
A one-time job stays in the CronTrigger table after it has fired, in a completed state. Clean these up if you create many.
Building expressions in code
Hard-coded expressions are fine for a single job. When several jobs share a pattern, or an admin supplies the time through a custom setting, assembling the string in code helps. Use a small helper that checks its inputs, so a bad value fails with a clear message that names the problem instead of an opaque scheduling error.
public class CronBuilder {
// Every day at the given hour and minute.
public static String daily(Integer hour, Integer minute) {
check('hour', hour, 0, 23);
check('minute', minute, 0, 59);
return '0 ' + minute + ' ' + hour + ' * * ?';
}
// Every day of the chosen weekdays, e.g. 'MON-FRI' or 'MON,WED,FRI'.
public static String weekdays(String days, Integer hour, Integer minute) {
check('hour', hour, 0, 23);
check('minute', minute, 0, 59);
if (String.isBlank(days)) {
throw new IllegalArgumentException('days must not be blank');
}
return '0 ' + minute + ' ' + hour + ' ? * ' + days;
}
// Every N minutes, starting at minute 0 of each hour.
public static String everyMinutes(Integer step) {
check('step', step, 1, 59);
return '0 0/' + step + ' * * * ?';
}
private static void check(String name, Integer value, Integer low, Integer high) {
if (value == null || value < low || value > high) {
throw new IllegalArgumentException(
name + ' must be between ' + low + ' and ' + high + ' but was ' + value
);
}
}
public class IllegalArgumentException extends Exception {}
}The class compiles as written, so you can use it with the job from earlier chapters:
String cronExp = CronBuilder.weekdays('MON-FRI', 6, 30);
System.debug(cronExp); // 0 30 6 ? * MON-FRI
Id jobId = System.schedule('Escalate stale cases weekdays', cronExp, new EscalateStaleCases());The helper builds the string only. Whether the string describes a time that exists is still decided by System.schedule, so keep that call where an exception can be seen and handled.
Common errors
- Both day fields set.
0 0 8 15 * MONfails because Dayofmonth and Dayofweek both carry a value. Replace one with?. *instead of?.0 0 13 * * *fails for the same reason. The final required field must be?when Dayofmonth is*.- Wrong field count. Leaving out the seconds field is the usual cause. A five-field Unix expression such as
0 13 * * *does not work. Add the seconds field and the?. - Numeric weekdays shifted by one.
2is Monday. Use names. - Out-of-range values. Hour
24or minute60is rejected. Midnight is hour0. - A date that does not exist.
0 0 0 31 2 ?asks for 31 February. UseLfor "last day of the month". - Past year. An expression with only past dates fails with the "will never fire" error.
- Duplicate names. Two jobs cannot share the name if the same name is already scheduled. This is not a cron problem, but it often appears in the same error handling. Include a unique element in the name if you create the same job more than once.
Test an expression before you rely on it
Reading an expression carefully is faster than debugging a job that fires on the wrong day, but you should also check. The most direct check is to schedule the job in a sandbox and read NextFireTime from its CronTrigger, a query shown in the monitoring chapter. If NextFireTime is not the moment you intended, fix the expression before moving on. A unit test can confirm the string a helper produces without scheduling anything:
@IsTest
private class CronBuilderTest {
@IsTest
static void buildsExpectedStrings() {
System.assertEquals('0 0 13 * * ?', CronBuilder.daily(13, 0));
System.assertEquals('0 30 6 ? * MON-FRI', CronBuilder.weekdays('MON-FRI', 6, 30));
System.assertEquals('0 0/15 * * * ?', CronBuilder.everyMinutes(15));
}
@IsTest
static void rejectsOutOfRangeHour() {
try {
CronBuilder.daily(24, 0);
System.assert(false, 'Expected an exception');
} catch (CronBuilder.IllegalArgumentException e) {
System.assert(e.getMessage().contains('hour'));
}
}
}Exercise
Write a cron expression that runs a job at 7:45 AM on the last day of every month. Then explain what is wrong with 0 45 7 L * *.
Show answer
Use 0 45 7 L * ?. Seconds is 0, minutes is 45, hours is 7, Dayofmonth is L for the last day, Month is *, and Dayofweek is ?. The expression 0 45 7 L * * puts a value (L) in Dayofmonth and * in Dayofweek, so both day fields are set. One of the two must be ?, so System.schedule rejects it.
Exercise
What days does 0 0 9 ? * 2#1 run on, and what does 0 0 9 ? * 2/2 mean differently from it?
Show answer
2#1 is the first Monday of each month, because 2 is Monday and #1 selects the first occurrence. The second expression uses 2/2 as an increment in Dayofweek: it starts at day 2 (Monday) and steps by 2, so it runs on Monday, Wednesday and Friday of every week at 9:00 AM. The first form runs once a month, the second runs three times a week.
Exercise
A teammate wants a job to run every 20 minutes and writes 0 0/20 * * * ?. A second teammate wants every 25 minutes and writes 0 0/25 * * * ?. Do both give an even interval? Explain.
Show answer
The first does. It fires at :00, :20 and :40, then at :00 of the next hour, so the gap is always 20 minutes. The second does not. It fires at :00, :25 and :50, then restarts at :00 of the next hour, so the gap from :50 to :00 is only 10 minutes. Increments restart at each hour, so only steps that divide 60 evenly give a constant interval.