# How do Cron expressions work in Scheduled Apex, and what are the rules for formatting them correctly?

**Topic:** Apex · **Difficulty:** Medium · **Tags:** Apex, Asynchronous Apex, Scheduled Apex

Read it on the site: https://www.forcechallenges.com/interview-questions/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, `L` last, `W` nearest 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:**
```apex
public class NightlyCleanup implements Schedulable {
    public void execute(SchedulableContext sc) {
        Database.executeBatch(new AccountCleanupBatch(), 200);
    }
}
// Daily at 02:00
System.schedule('Nightly Cleanup', '0 0 2 * * ?', new NightlyCleanup());
// Weekdays 10:15:       '0 15 10 ? * MON-FRI'
// Last day of month:    '0 0 23 L * ?'
// First Monday monthly: '0 0 6 ? * 2#1'
```

**Hidden gotchas & must-remember points:**
- Using `*` or a value in both day-of-month and day-of-week causes an error; one must be `?`.
- Day of week 1 is Sunday, not Monday.
- Job names must be unique per schedule; duplicates throw an exception.
- Maximum 100 scheduled Apex jobs per org.
- A class with a scheduled job pending cannot be deployed or edited unless the deployment setting allows it.
- Daylight saving shifts follow the scheduling user's time zone.

**Best practice:** Keep `execute()` as a thin launcher and give schedules descriptive, unique names.

---
Source: ForceChallenges · last updated 2026-11-02
