Sub topic 11
Designing reliable scheduled jobs
This chapter assumes you can write a Schedulable class, build a cron expression, call System.schedule, query CronTrigger, and write a basic Apex test. It pulls those pieces into a set of design habits. Each habit guards against a failure that is hard to notice, because nobody is watching when a scheduled job runs.
Why scheduled jobs fail quietly
A scheduled job has no user waiting on it. If it throws an exception or processes only part of the data, nobody sees an error on screen. Salesforce may send an email to the user who scheduled the job. Otherwise you find out later, when records are stale. Reliable design is mostly about making failures visible and making reruns safe.
The diagram shows the shape that works well. The scheduled class stays small. It decides what to do, then hands the work to a class built for it.
Keep the Schedulable class thin
The execute method runs under the normal limits for one transaction. The first example in this tutorial used one query and one bulk DML statement with LIMIT 200, which is fine for small volumes. When the data can grow, the class should only start a batch job, as in NightlyTaskCleanup. Each batch chunk then gets its own set of governor limits.
A thin class also makes testing easier. The logic lives in a class you can call directly, and the schedulable wrapper stays trivial.
Make every run safe to repeat
A job can run late, run twice after someone reschedules it by mistake, or fail halfway and be run again by hand. Design the work so a second run does no harm.
- Select only records that still need work.
EscalateStaleCasesfilters onPriority != 'High', so a second run finds nothing new. - Avoid actions that add up on every run, such as incrementing a counter or creating a new child record for each parent each night. If you must create records, check first whether one already exists.
- Use a status or date field, such as
Last_Processed__c, to mark finished records when no natural filter exists.
Write for bulk and for the query limit
Never assume a small number of records. Use one query and one DML statement per transaction, as in the examples. Keep SOQL selective, which means filtering on indexed fields such as CreatedDate where possible, so the query does not time out as the table grows. Remember that a LIMIT clause quietly skips records beyond it. If you use one, make sure the next run picks up the remainder. Otherwise switch to a batch job, which processes all matching records in chunks.
Handle errors on purpose
An unhandled exception ends the transaction and rolls back its changes. Partial-success DML lets good records save while bad ones are reported.
public class EscalateStaleCasesSafe 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';
}
List<Database.SaveResult> results = Database.update(stale, false);
for (Integer i = 0; i < results.size(); i++) {
if (!results[i].isSuccess()) {
System.debug(LoggingLevel.ERROR,
'Case ' + stale[i].Id + ' failed: ' + results[i].getErrors()[0].getMessage());
}
}
}
}System.debug output is only useful while someone reads logs. For production jobs, write failures to a custom log object or send an email or platform event from the finish method of a batch class. Choose a place someone actually checks.
Plan for the limits
Treat the restrictions from the earlier chapter as design inputs.
| Concern | Design response |
|---|---|
| Only 100 scheduled jobs at one time | Combine related work into one job instead of one job per task |
| Callouts not allowed directly from `execute` | Start a batch (with `Database.AllowsCallouts`) or a queueable class that makes the callout |
| Batch starts count against the limit on queued batch jobs | Start one batch per run, and check for running jobs before starting more |
| Job may start later than the set time | Do not depend on the exact second. Use date ranges, not exact times, in filters |
Name, document and own your jobs
- Give each job a clear, unique name, such as
Escalate stale cases - daily 13:00. Names are how people find it inCronTriggerand in Setup. - Keep scheduling code in one place, for example a static
schedule()method on the class, so the cron expression is not copied across scripts. - Check for an existing job before scheduling, so a deployment script does not create duplicates.
- Know who owns the job. The job runs as the user who scheduled it, so a deactivated user can break it. Prefer a stable integration user.
public class EscalateStaleCasesScheduler {
public static final String JOB_NAME = 'Escalate stale cases - daily 13:00';
public static void ensureScheduled() {
List<CronTrigger> existing = [
SELECT Id FROM CronTrigger WHERE CronJobDetail.Name = :JOB_NAME
];
if (existing.isEmpty()) {
System.schedule(JOB_NAME, '0 0 13 * * ?', new EscalateStaleCases());
}
}
}Test and watch what you ship
Test the business logic directly, and keep a small test that checks the job schedules correctly, as in EscalateStaleCasesTest. After deployment, query CronTrigger for State and NextFireTime to confirm the job is waiting. A job whose NextFireTime is empty has finished its schedule and will not run again.
Exercise
A nightly job selects up to 200 accounts and adds 1 to a Review_Count__c field on each. It fails halfway one night and an admin runs it again by hand. What goes wrong, and how would you redesign it?
Show answer
Accounts updated before the failure are incremented twice, so the counter is wrong. The job is not safe to repeat. Redesign it so a run only selects accounts not yet processed (for example a Last_Reviewed__c date filter set to the run date), or set the field to a computed value instead of adding to it. Move large volumes into a batch class and log failures from finish.
Exercise
Why should the Schedulable class usually only call Database.executeBatch, and what do you gain from that?
Show answer
Each batch chunk runs in its own transaction with its own governor limits, so volume growth does not break the job. The thin wrapper is also easy to test, and the processing logic can be reused or run manually.