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:
public class NightlyCleanupScheduler implements Schedulable {
public void execute(SchedulableContext sc) {
Database.executeBatch(new ContactCleanup(), );
}
}