# How does Scheduled Apex work using the Schedulable interface, and what are best practices for cron scheduling?

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

Read it on the site: https://www.forcechallenges.com/interview-questions/how-does-scheduled-apex-work-using-the-schedulable-interface-and-what-are-best-practices-for-cron-scheduling

## Answer

**Basics:** Use it for nightly rollups, cleanups, or periodic syncs. You can also schedule via Setup > Apex Classes > Schedule Apex, which is easy but limited to daily/weekly style options.

**How it works:** Write a class with `execute(SchedulableContext sc)`. Schedule with `System.schedule('Nightly Job', '0 0 2 * * ?', new MyScheduler());`. The cron format is Seconds Minutes Hours DayOfMonth Month DayOfWeek [Year]; use `?` for the unused day field. The job appears as a CronTrigger and in Scheduled Jobs. At the time, the platform runs execute as the user who scheduled it, in system mode.

**Advanced / deep dive:** Maximum 100 scheduled Apex jobs per org. Execution may be delayed when the platform is busy. Callouts cannot be made directly from execute; start a Queueable with AllowsCallouts or a Batch with AllowsCallouts. If five batch jobs are already active, a job started from the scheduler goes to the Flex Queue. For sub-hourly cadence, consider a self-rescheduling Queueable with delay or multiple jobs, verifying behaviour. Abort via System.abortJob(cronTriggerId). Alternatives: schedule-triggered Flow, which is preferable for declarative work.

**Code / config example:**
```apex
public class NightlyCleanupScheduler implements Schedulable {
    public void execute(SchedulableContext sc) {
        Database.executeBatch(new ContactCleanup(), 200);
    }
}
// Every day at 02:00
// System.schedule('Nightly cleanup', '0 0 2 * * ?', new NightlyCleanupScheduler());
```

**Hidden gotchas & must-remember points:**
- Classes with scheduled jobs cannot be modified or deployed until the jobs are removed.
- Limit of 100 scheduled jobs.
- Use `?` in either day-of-month or day-of-week, not both as values.
- In tests, schedule runs on Test.stopTest().
- Schedules do not move automatically between sandboxes; recreate after refresh.
- Scheduled jobs run with the scheduling user's context; if the user is deactivated, review.

**Best practice:** Keep scheduler classes tiny, delegate to Batch, and manage schedules via a setup script or custom setting.

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