How do Cron expressions work in Scheduled Apex, and what are the rules for formatting them correctly?
Answer
Basics: To run an Apex class on a schedule, implement Schedulable, then call System.schedule(name, cronExpression, instance) or use Setup, Apex Classes, Schedule Apex. The cron string tells Salesforce when to fire.
How it works:
- Fields: seconds (0-59), minutes (0-59), hours (0-23), day of month (1-31), month (1-12 or JAN-DEC), day of week (1-7 or SUN-SAT, 1 = Sunday), optional year.
- Special characters:
*all values,?no specific value (only for day fields),-range,,list,/increment,Llast,Wnearest weekday,#nth weekday of the month. - The job runs in the time zone of the user who scheduled it.
Advanced / deep dive: Cron granularity is effectively hourly at the finest through the UI, but with the Apex System.schedule you can use minute-level expressions; for several runs per hour, schedule multiple jobs or use System.scheduleBatch(batch, name, minutesFromNow, scope) for one-time delays. Salesforce guarantees a start no earlier than the time, not exactly then; heavy load can delay it. The scheduled execute() should do little: typically it launches a batch or queueable, because scheduled code has synchronous limits and cannot run callouts directly. Each scheduled job counts toward the 100-job org limit and also toward the daily async executions.
Code / config example:
public class NightlyCleanup implements {
{
Database.executeBatch( (), );
}
}
System.schedule(, , ());