Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 36 ยท Asynchronous Apex

Scheduled Apex and Cron Expressions

Learn Scheduled Apex: implement Schedulable, write cron expressions, schedule from code or Setup, launch batches on a timer and test schedules, with a runnable Java cron stand-in.

Some work belongs on a clock: archive stale records every night, send a Monday summary, recalculate scores each hour. Scheduled Apex runs a class at a time you define, using a cron expression. The scheduled class is usually tiny: its job is to start something bigger, such as a batch job or a queueable.

Scheduling needs an org. The Apex below is read-only; the runnable examples are Java stand-ins that model cron matching and a scheduler.

The Schedulable interface

Implement Schedulable and its single method execute:

APEX
public with sharing class NightlyCleanup implements Schedulable {
    public void execute(SchedulableContext sc) {
        Database.executeBatch(new StaleLeadCleanup(), 200);
    }
}

Keep execute short and delegate. A scheduled job runs in a normal transaction, and callouts are not allowed directly from it, so use a batch or queueable that allows callouts.

Scheduling in code

System.schedule takes a job name, a cron expression and an instance:

APEX
String cron = '0 0 2 * * ?';   // every day at 02:00
Id jobId = System.schedule('Nightly lead cleanup', cron, new NightlyCleanup());

Run this once from the Developer Console's anonymous Apex window; the schedule then persists. Job names must be unique among scheduled jobs. You can also schedule from Setup, Apex Classes, Schedule Apex, which offers a friendly UI with day and time pickers for daily or weekly schedules.

Cron expressions

An Apex cron expression has six or seven fields:

Text
Seconds Minutes Hours DayOfMonth Month DayOfWeek [Year]
Expression Meaning
0 0 2 * * ? Every day at 02:00
0 30 8 ? * MON-FRI Weekdays at 08:30
0 0 0 1 * ? The first day of every month at midnight
0 0 12 ? * 2#1 The first Monday of each month at noon
0 0 6 L * ? The last day of the month at 06:00

The ? means "no specific value" and is required in exactly one of DayOfMonth and DayOfWeek (you cannot specify both). L means last, # picks the nth weekday. The Setup page only offers a daily or weekly start time, but a cron expression passed to System.schedule can name specific minutes. For jobs more frequent than hourly, teams schedule several jobs offset by minutes (below) or use a queueable that re-enqueues itself.

APEX
// Run at minute 0, 15, 30 and 45 by scheduling four jobs
String[] minutes = new String[]{ '0', '15', '30', '45' };
for (String m : minutes) {
    System.schedule('Poll ' + m, '0 ' + m + ' * * * ?', new PollJob());
}

Limits and management

  • A maximum of 100 scheduled Apex jobs at one time.
  • Scheduled jobs run as the user who scheduled them (so keep a deliberate integration user in mind).
  • Monitor under Setup, Scheduled Jobs, or query CronTrigger:
APEX
CronTrigger ct = [SELECT Id, CronExpression, NextFireTime, State
                  FROM CronTrigger WHERE Id = :jobId];
System.debug(ct.NextFireTime);
  • Remove a job with System.abortJob(jobId).
  • Deployments can be blocked by classes with pending scheduled jobs. Abort or reschedule jobs before deploying changes to that class (see deployment).

Testing schedules

A test cannot wait for a real clock. Instead, schedule the job inside startTest/stopTest and, if desired, call execute directly. Scheduled jobs queued in a test run at stopTest.

APEX
@isTest
static void nightlyJobIsScheduled() {
    Test.startTest();
    Id jobId = System.schedule('Test nightly', '0 0 2 * * ?', new NightlyCleanup());
    Test.stopTest();

    CronTrigger ct = [SELECT CronExpression, TimesTriggered FROM CronTrigger WHERE Id = :jobId];
    Assert.areEqual('0 0 2 * * ?', ct.CronExpression);
    Assert.areEqual(0, ct.TimesTriggered);
}

Try the idea: reading a cron expression (Java stand-in)

Java Stand-in: a simplified cron matcher (Java)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Five weekday mornings in one week gives five fires. The real parser also understands ranges in every field, L, W and #.

Try the idea: a scheduler that starts a batch (Java stand-in)

Java Stand-in: scheduled job delegates to a batch (Java)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Good practice

  • Keep the scheduled class a thin launcher; put logic in a batch or queueable.
  • Give jobs descriptive unique names, and store the schedule creation in a setup script (or a post-deploy step) so it is reproducible.
  • Decide who the job runs as; if that user is deactivated the job stops.
  • Prefer Flow scheduled paths for simple declarative tasks; use Apex when you need code.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does the cron expression 0 0 2 * * ? mean?

    Fields are seconds, minutes, hours, day of month, month, day of week: second 0, minute 0, hour 2, every day.
  2. 2. Why is ? needed in a cron expression?

    You cannot specify both day of month and day of week, so one of them must be ?.
  3. 3. What should a scheduled class's execute method usually do?

    It is a launcher: callouts are not allowed directly from the schedulable and heavy work belongs in async classes.
  4. 4. How many scheduled Apex jobs can exist at once?

    An org can hold up to 100 scheduled Apex jobs.

Summary

  • Implement Schedulable and schedule with System.schedule(name, cron, job).
  • Cron fields: seconds, minutes, hours, day of month, month, day of week, optional year.
  • Keep schedulables thin; start batches or queueables from them.
  • Max 100 scheduled jobs; monitor with CronTrigger; test by scheduling inside startTest/stopTest.

Next: Lightning Web Components: Your First Component