Sub topic 11
Designing Reliable Scheduled Jobs
This chapter assumes you can already write a Schedulable class, build a cron expression, call System.schedule, and query CronTrigger. It also assumes you know the basics of Batch Apex, governor limits, and how to write an Apex test. Earlier chapters covered the mechanics. This chapter covers how to build jobs that keep working after the person who wrote them has moved on.
Why scheduled jobs fail in production
A scheduled job has no user watching it. When a trigger fails, someone sees the error on screen. When a scheduled job fails, the next run may simply try again, or the job may stop and nobody notices until a report looks wrong. Most failures come from a short list of causes:
- The data volume grew past what one
executecall can handle. - A record fails validation and takes the whole run down with it.
- The job was scheduled twice, or not at all, after a deployment.
- The job started later than expected, or overlapped with a previous run.
- The logic is buried inside the scheduled class, so it can only be tested by waiting for a clock.
The practices below address each one.
Keep the scheduled class thin
The execute method should do very little. Put the business logic in a separate class with a plain static method. This gives you three benefits:
- You can test the logic directly, without scheduling anything.
- You can call the same logic from a button, a Flow action, or an anonymous Apex window when you need to run it by hand.
- You can switch from direct processing to Batch Apex later without rewriting the logic.
Here is a service class for the stale-case example from earlier in the chapter series:
public with sharing class StaleCaseService {
public class Result {
public Integer updated = 0;
public Integer failed = 0;
public List<String> errors = new List<String>();
}
public static Result escalate(Integer maxRows) {
Result res = new Result();
List<Case> stale = [
SELECT Id, Priority
FROM Case
WHERE IsClosed = false
AND Priority != 'High'
AND CreatedDate < LAST_N_DAYS:7
ORDER BY CreatedDate
LIMIT :maxRows
];
for (Case c : stale) {
c.Priority = 'High';
}
List<Database.SaveResult> saves = Database.update(stale, false);
for (Integer i = 0; i < saves.size(); i++) {
if (saves[i].isSuccess()) {
res.updated++;
} else {
res.failed++;
res.errors.add(stale[i].Id + ': ' + saves[i].getErrors()[0].getMessage());
}
}
return res;
}
}Three design choices in this class matter:
- It is bulk-safe. One query and one DML call handle every record.
- It is bounded. The
LIMIT :maxRowsclause keeps the job inside governor limits however much data exists. - It tolerates partial failure.
Database.update(stale, false)saves the records that pass and reports the ones that do not, so one bad record does not roll back the rest.
The scheduled class then becomes a wrapper:
public class EscalateStaleCasesJob implements Schedulable {
public void execute(SchedulableContext sc) {
StaleCaseService.Result res = StaleCaseService.escalate(200);
System.debug(LoggingLevel.INFO,
'Job ' + sc.getTriggerId() + ' updated=' + res.updated + ' failed=' + res.failed);
if (res.failed > 0) {
System.debug(LoggingLevel.ERROR, String.join(res.errors, '\n'));
}
}
}Make every run idempotent
An idempotent job gives the same end state whether it runs once or three times. This matters because runs can be repeated: an admin triggers one by hand, a delayed run overlaps the next one, or a batch is retried after an error.
The stale-case job is idempotent because its filter includes Priority != 'High'. A case that was already escalated is never selected again. Compare that with a job that adds 10 to a counter field on every run. Run it twice and the data is wrong.
To make a job idempotent:
- Select only records that still need work, and make the job's own update remove them from that selection (a status change, a processed flag, a timestamp).
- Prefer setting a value (
Priority = 'High') over changing it relative to its current value (Amount = Amount * 1.1). - Use upsert with an external ID when the job creates records, so a rerun updates instead of duplicating.
Bound the work, or hand it to Batch Apex
A scheduled execute method runs under the normal synchronous governor limits: 100 SOQL queries, 150 DML statements, 50,000 query rows, and 10,000 DML rows. A LIMIT clause protects you, but it also means records beyond the limit wait for the next run. For a daily job on a table that grows by thousands of rows a day, that backlog never clears.
Use this rule of thumb:
| Situation | Approach |
|---|---|
| A few hundred records at most, and bounded by business rules | Process directly in `execute` with a `LIMIT` |
| Thousands of records, or volume that grows | Start a Batch Apex job from `execute` |
| Work that needs a callout | Batch with `Database.AllowsCallouts`, or a Queueable that implements `Database.AllowsCallouts` |
Callouts are not allowed directly from execute in a scheduled class. Start an asynchronous job that is allowed to make them.
When the scheduled class starts a batch, check the batch queue first if your org runs many batch jobs. Salesforce allows up to five queued or active batch jobs at once. Past that, Database.executeBatch places the job in the flex queue, up to 100 held jobs. A busy org can therefore delay your batch by a long time, so do not assume the work finishes right after the scheduled start.
Schedule once, and only once
The most common operational mistake is duplicate schedules. Someone runs the scheduling snippet in the Developer Console during a release, and again during the next release. Now the job runs twice a day. Each System.schedule call needs a unique name within the org, so a repeat with the same name fails with an error, but a slightly different name succeeds silently.
A helper that removes any existing job with the same name before scheduling makes the operation safe to repeat:
public class JobScheduler {
public static Id replaceSchedule(String jobName, String cronExp, Schedulable job) {
for (CronTrigger ct : [
SELECT Id
FROM CronTrigger
WHERE CronJobDetail.Name = :jobName
]) {
System.abortJob(ct.Id);
}
return System.schedule(jobName, cronExp, job);
}
}Run it from a post-deployment script or an install handler:
JobScheduler.replaceSchedule(
'Escalate stale cases',
'0 0 13 * * ?',
new EscalateStaleCasesJob()
);Plan for late starts, overlap and time zones
The scheduler queues a job at its cron time. The job starts when resources are available, which can be later than the scheduled minute. Design with that in mind:
- Do not rely on a run starting at exactly 13:00. Use a window or a "since last successful run" timestamp instead of "records created in the last hour".
- Do not assume a run finishes before the next one starts. A batch started from a daily job could still be running at the next fire time if the data is large. Idempotent selection protects you here. For jobs that must never overlap, query
AsyncApexJobfor active jobs of your batch class and skip the run if one exists. - The cron expression is evaluated in the time zone of the user who scheduled the job. After a daylight saving change, or after a different admin reschedules the job, the clock time can shift. Record the intended time zone in the job name or a documentation comment.
- Salesforce limits an org to 100 scheduled Apex jobs at one time. Combine related work into one job rather than creating one per record or per customer.
Here is an overlap check for a batch started by a scheduled class:
public class NightlyTaskCleanupJob implements Schedulable {
public void execute(SchedulableContext sc) {
Integer active = [
SELECT COUNT()
FROM AsyncApexJob
WHERE JobType = 'BatchApex'
AND ApexClass.Name = 'ArchiveOldTasksBatch'
AND Status IN ('Holding', 'Queued', 'Preparing', 'Processing')
];
if (active == 0) {
Database.executeBatch(new ArchiveOldTasksBatch(), 200);
} else {
System.debug(LoggingLevel.WARN, 'Skipped: previous cleanup batch still running');
}
}
}Handle errors so they are visible
An uncaught exception in execute ends that run, and the failure appears only in Setup under Apex Jobs and in the debug logs, if logging was on. The job stays scheduled and tries again at the next cron time. This is usually what you want, but you still need to know it happened.
Practical steps:
- Catch expected failures (validation errors, locked rows) and report them. Let unexpected exceptions propagate so the platform marks the run as failed.
- Write outcomes somewhere durable. A custom object such as
Job_Run_Log__cwith fields for job name, start time, rows updated, rows failed, and a message is more useful than debug logs, which expire. - Notify someone. Send an email with
Messaging.sendEmail, or publish a platform event that a Flow turns into a notification. Alert on failures, and also on silence: a job that should log every day and has not logged for two days is as urgent as a job that logged an error. - In a batch class, use the
finishmethod to readAsyncApexJobforNumberOfErrorsand send a summary.
Make the job configurable without a deployment
Hardcoded values force a code deployment for every small change. Move values that operations staff might adjust into Custom Metadata Types or Custom Settings:
- The number of days that counts as "stale".
- The batch size.
- A kill switch (
Enabled__c) that makesexecutereturn immediately.
A kill switch is worth the few lines it costs. When a job is damaging data, the fastest safe response is to turn it off from Setup, not to deploy a fix or to abort and later recreate the schedule.
Keep the cron expression itself in the scheduling script, not in a setting that the job reads, unless you also build the code that reschedules the job when the setting changes.
Test the logic and the schedule separately
A good test suite for a scheduled job has two parts.
Logic tests call the service class directly. They need no scheduler and run fast. Use Test.setCreatedDate to make a record look old:
@IsTest
private class StaleCaseServiceTest {
@IsTest
static void escalatesOnlyOldOpenCases() {
Case oldCase = new Case(Subject = 'Old', Priority = 'Low', Status = 'New');
Case newCase = new Case(Subject = 'New', Priority = 'Low', Status = 'New');
insert new List<Case>{ oldCase, newCase };
Test.setCreatedDate(oldCase.Id, Datetime.now().addDays(-10));
Test.startTest();
StaleCaseService.Result first = StaleCaseService.escalate(200);
StaleCaseService.Result second = StaleCaseService.escalate(200);
Test.stopTest();
System.assertEquals(1, first.updated);
System.assertEquals(0, second.updated, 'Second run must find nothing to do');
System.assertEquals('High', [SELECT Priority FROM Case WHERE Id = :oldCase.Id].Priority);
System.assertEquals('Low', [SELECT Priority FROM Case WHERE Id = :newCase.Id].Priority);
}
}The second call checks idempotency directly.
Schedule tests confirm that scheduling works and that the cron expression is stored. Use a date far in the future so the job does not fire during the test, as shown in the earlier testing chapter. Also test JobScheduler.replaceSchedule by calling it twice and asserting that exactly one CronTrigger exists with that name.
A pre-release checklist
Before you ship a scheduled job, check each item:
executedelegates to a service or batch class.- Every query is bounded or runs inside Batch Apex.
- Running the job twice in a row leaves the data in the same state as running it once.
- Failures are logged somewhere that lasts, and someone is told.
- Scheduling is done by a repeatable script that replaces an existing job.
- Tunable values and a kill switch live in metadata, not code.
- Tests cover the logic, the second-run case, and the schedule itself.
- The release plan handles pending jobs during deployment.
Exercise
A scheduled job adds a $5 fee to every invoice with Status = 'Overdue'. It runs nightly. An admin runs it by hand one afternoon to test it, and the nightly run follows. What went wrong, and how would you redesign the job?
Show answer
The job is not idempotent. Each run selects the same overdue invoices and adds another $5, so those invoices are charged twice. Redesign it so a run marks which invoices it has processed, for example a LateFeeApplied_c checkbox or a LateFeeDate_c field. Select only invoices where that field is empty, and set it in the same update that adds the fee. A repeated run then finds nothing to do. Moving the fee logic into a service class also lets you test the second-run case directly.
Exercise
Your org schedules 'Nightly sync' with System.schedule from a script that runs on every deployment. After three releases, the sync runs three times each night. Write the Apex that prevents this.
Show answer
Abort any existing job with the same name before scheduling. For example: for (CronTrigger ct : [SELECT Id FROM CronTrigger WHERE CronJobDetail.Name = 'Nightly sync']) { System.abortJob(ct.Id); } followed by System.schedule('Nightly sync', cronExp, new NightlySyncJob());. Wrapping this in a helper method such as JobScheduler.replaceSchedule makes the script safe to run on every deployment, and it leaves one CronTrigger with that name.
Exercise
A scheduled class must call an external web service for each of 5,000 accounts. Which asynchronous pattern should the scheduled class start, and why can't it make the callouts itself?
Show answer
Scheduled execute methods cannot make callouts directly. The class should start a Batch Apex job that implements Database.AllowsCallouts, so the 5,000 records are processed in chunks, each chunk getting its own governor limits and its own callouts. A Queueable that implements Database.AllowsCallouts also works for smaller or chained workloads. Use a small batch size so that each execute call stays inside the callout limit of 100 per transaction.