Sub topic 2
Writing a Schedulable class
This chapter assumes you can write Apex classes, run SOQL queries and DML statements, and know the main governor limits. It also assumes you can open the Developer Console. Here you write the class that a scheduled job runs. Cron expressions, System.schedule, the Setup UI, monitoring and testing each get their own chapter, so this one only touches them where the class design depends on them.
What the interface requires
Schedulable is a built-in Apex interface with one method:
global interface Schedulable {
void execute(SchedulableContext sc);
}To make a class schedulable, declare implements Schedulable and provide execute with exactly that signature. The method must return void, take one SchedulableContext parameter, and be public or global. Use global only when the class must be visible outside its managed package.
Here is a complete class that escalates old open cases:
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;
}
}The method follows the same bulk pattern as trigger code. It makes one query, changes records in memory, and issues one update. DML inside the loop would spend one statement per record against the 150-statement limit.
The LIMIT 200 is a deliberate cap. It keeps one run small and predictable. The cost is that a backlog of 5,000 stale cases takes many days to clear. The section on handing work to Batch Apex covers the alternative.
What happens when the job fires
Scheduling the class does not run it. It stores a job record and a serialized copy of your object. At the scheduled time the platform restores that object and calls execute in its own transaction. No user session, trigger or page is involved.
Three consequences follow from this lifecycle.
- Every run is a new transaction with a fresh set of governor limits.
- Nothing in static variables survives from one run to the next.
- The state of your instance is whatever it was when the job was scheduled, not what it was when the last run ended.
Passing configuration through the constructor
Because the platform serializes the instance, instance fields are the supported way to give a job its settings. Set them in a constructor and read them in execute:
public class EscalateStaleCasesConfigurable implements Schedulable {
private Integer staleDays;
public EscalateStaleCasesConfigurable() {
this(7);
}
public EscalateStaleCasesConfigurable(Integer staleDays) {
this.staleDays = staleDays;
}
public void execute(SchedulableContext sc) {
Datetime cutoff = Datetime.now().addDays(-staleDays);
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;
}
}Scheduling it with new EscalateStaleCasesConfigurable(14) stores the value 14. The no-argument constructor matters when you schedule from Setup, because the platform creates the instance and you cannot supply arguments. It also gives the job a sensible default.
Keep these rules in mind for instance state:
- Fields must be serializable. Primitives, SObjects, collections of those and simple custom types are fine.
transientfields come back asnullwhen the instance is restored.- Changes to fields made inside
executedo not carry over to the next run. A job that needs a counter or a "last processed" marker must store it in a custom setting, custom metadata, or a record. - A value captured at scheduling time can go stale. If the setting changes often, read it inside
executeinstead.
Keep execute thin
A common pattern is to make execute a short entry point that calls a service class. The scheduler becomes one of several callers of the same logic. A button, a trigger handler, or a test can call the service directly without scheduling anything.
public with sharing class CaseEscalationService {
public static Integer escalateStale(Integer staleDays, Integer maxRows) {
Datetime cutoff = Datetime.now().addDays(-staleDays);
List<Case> stale = [
SELECT Id, Priority
FROM Case
WHERE IsClosed = false
AND Priority != 'High'
AND CreatedDate < :cutoff
LIMIT :maxRows
];
for (Case c : stale) {
c.Priority = 'High';
}
update stale;
return stale.size();
}
}
public class EscalateStaleCasesJob implements Schedulable {
public void execute(SchedulableContext sc) {
Integer changed = CaseEscalationService.escalateStale(7, 200);
System.debug('Escalated ' + changed + ' cases');
}
}This split also makes tests simpler. You can verify the business rule by calling escalateStale and checking the results. Then a single small test confirms that the schedule is wired up.
Sharing and the running user
Scheduled Apex runs without a user interface, but the class's sharing declaration still decides whether record sharing rules apply. A top-level class with no sharing keyword runs without sharing by default. For anything that touches business data, state your intent explicitly with with sharing, without sharing or inherited sharing.
The job is also tied to the user who scheduled it. Audit fields such as LastModifiedById on records the job changes usually show that user. Consider that when choosing who schedules a production job. If that user is deactivated, plan for rescheduling the job under a stable administrative or integration user.
Exceptions and failed runs
An unhandled exception in execute ends that run and rolls back the transaction. The job is marked as failed for that run, and the platform sends an error notification to the user who scheduled it. A recurring job is not removed. It stays scheduled and fires again at the next time in its timetable.
This matters because a bug can fail every night without anyone noticing. Decide per job how to handle failure:
- Wrap the work in
try/catchand write the error to a log object or custom field. - Use
Database.update(records, false)when partial success is acceptable, and inspect theSaveResultlist for failures. - Rethrow only when you want the platform to record the run as failed.
public class SafeEscalateJob implements Schedulable {
public void execute(SchedulableContext sc) {
try {
CaseEscalationService.escalateStale(7, 200);
} catch (DmlException e) {
System.debug(LoggingLevel.ERROR, 'Escalation failed: ' + e.getMessage());
throw e;
}
}
}Here the job logs the problem and then rethrows, so the failure still shows in the platform's job history.
Callouts are not allowed directly
You cannot make a synchronous HTTP callout from execute. If the job needs to call an external service, hand the call to an asynchronous method such as @future(callout=true). You can also start a Batch Apex job whose class implements Database.AllowsCallouts. The next chapters return to handing work off in detail.
Common compile and design errors
| Symptom | Cause | Fix |
|---|---|---|
| Compile error that the class must implement the method `execute(System.SchedulableContext)` | Method missing, misspelled, or has a different parameter list | Use `public void execute(SchedulableContext sc)` exactly |
| Compile error about method visibility | `execute` declared `private` or with no access modifier | Declare it `public` or `global` |
| Constructor value is not what you expected on a later run | The instance was serialized when the job was scheduled | Re-schedule to change it, or read the value at run time |
| Field is `null` inside `execute` | The field is `transient` or not serializable | Remove `transient`, or reload the value inside `execute` |
| Job fails every run and nobody notices | Unhandled exception with no logging | Catch, log and notify, or monitor job history |
| Callout error in `execute` | Synchronous callouts are not allowed | Delegate to `@future(callout=true)` or a batch class that allows callouts |
Design checklist for a schedulable class
Before you hand the class over for scheduling, check these points:
- The
executemethod is bulkified: no queries or DML inside loops. - The volume of data is bounded, either by
LIMITor by delegating to Batch Apex. - The class declares its sharing mode.
- Settings that change are read at run time, and fixed settings come through the constructor.
- The business logic lives in a separate class that can be called without the scheduler.
- Failures are caught, logged or deliberately rethrown.
Exercise
A job class stores private Integer staleDays; set from its constructor. In execute, the code ends with staleDays = staleDays + 1;. The job is scheduled once with new MyJob(7) and runs daily. What value does staleDays hold at the start of the third run, and why?
Show answer
It is 7. The platform serializes the instance when the job is scheduled and restores that stored copy for each run. Changes made inside execute are not saved back to the instance, so each run starts from the originally scheduled value. To keep a counter across runs, store it in a record, custom setting, or custom metadata.
Exercise
You need a nightly job that calls an external REST service and then updates records based on the response. Why can't the execute method make the HTTP call directly, and what are two ways to arrange the work?
Show answer
Synchronous callouts are not supported from scheduled Apex. Two options are: call a method annotated with @future(callout=true) from execute, or start a Batch Apex job from execute whose class implements Database.AllowsCallouts and make the callout in the batch class.