Sub topic 2
Writing a Schedulable class
This chapter assumes you can write basic Apex classes, run SOQL queries and DML statements, and know the main governor limits. It also assumes you can open the Developer Console or Setup. Cron expressions and System.schedule get their own chapters. Here the goal is the class that the platform will run.
What a Schedulable class is
A Schedulable class is an Apex class that implements the Schedulable interface. The interface has one method, execute. When a scheduled time arrives, Salesforce creates an instance of your class and calls execute in its own transaction. No user or trigger is involved.
A minimal example
This class raises the priority of open cases that are more than seven days old.
public class EscalateStaleCases implements Schedulable {
public void execute(SchedulableContext sc) {
List<Case> stale = [
SELECT Id, Priority
FROM Case
WHERE IsClosed = false
AND Priority != 'High'
AND CreatedDate < LAST_N_DAYS:7
LIMIT 200
];
for (Case c : stale) {
c.Priority = 'High';
}
update stale;
}
}Four points matter here:
implements Schedulableis what makes the class eligible for scheduling. The class must be declaredpublicorglobal.executetakes aSchedulableContext. The platform passes it in. It carries the ID of the scheduled job, which a later chapter covers. You can ignore it for now.- There is one query and one DML statement. Both sit outside any loop, so the number of records changes the work done but not the number of statements.
LIMIT 200bounds the work. A scheduled job still runs under normal synchronous governor limits. Without a bound, a large backlog could hit the 50,000-row query limit or the 10,000-row DML limit and fail the whole run.
Keep `execute` thin
A scheduled job is hard to test by waiting for the clock. You can call execute directly from a test, but it is cleaner to put the logic in a method you can call on its own. Let execute delegate to it.
public class EscalateStaleCases implements Schedulable {
public void execute(SchedulableContext sc) {
escalate();
}
public static Integer escalate() {
List<Case> stale = [
SELECT Id, Priority
FROM Case
WHERE IsClosed = false
AND Priority != 'High'
AND CreatedDate < LAST_N_DAYS:7
LIMIT 200
];
for (Case c : stale) {
c.Priority = 'High';
}
update stale;
return stale.size();
}
}The same logic can now be called from a test, from anonymous Apex, or from another class. The scheduler only decides when it runs.
Constructors and state at scheduling time
You create the instance yourself when you schedule the job, so you can pass values through a constructor. Salesforce serializes the instance at that moment and restores it for each run.
public class EscalateStaleCases implements Schedulable {
private Integer ageInDays;
public EscalateStaleCases(Integer ageInDays) {
this.ageInDays = ageInDays;
}
public void execute(SchedulableContext sc) {
Date cutoff = Date.today().addDays(-ageInDays);
List<Case> stale = [
SELECT Id, Priority
FROM Case
WHERE IsClosed = false AND Priority != 'High' AND CreatedDate < :cutoff
LIMIT 200
];
for (Case c : stale) {
c.Priority = 'High';
}
update stale;
}
}The values stay fixed for the life of the scheduled job. To change ageInDays, abort the job and schedule it again with a new instance.
Common errors
| Problem | Cause | Fix |
|---|---|---|
| Compile error that the class must implement `execute` | The method name, parameter type or visibility is wrong | Declare `public void execute(SchedulableContext sc)` |
| Job fails with a limit exception | The query or DML is unbounded | Add a `LIMIT`, or hand the work to Batch Apex |
| Callout error | Synchronous callouts are not allowed from `execute` | Move the callout to a `@future(callout=true)` method, or to a Queueable or Batch class |
| Logic that depends on instance state breaks on later runs | Each run starts from the serialized instance | Store changing state in the database |
| Job cannot be changed after scheduling | The class reference is held by the scheduled job | Abort the job before editing or deleting the class, then schedule it again |
Exercise
A developer writes public class NightlySync implements Schedulable { public void execute() { ... } }. The class does not compile. What is wrong, and what should the method signature be?
Show answer
The execute method has no parameter, so it does not match the interface. It must be public void execute(SchedulableContext sc).