Sub topic 10
Combining the tools: a scheduler that starts a batch
This chapter assumes you know the earlier chapters: how Scheduled Apex uses cron expressions, how Batch Apex splits work into start, execute, and finish, and how Queueable jobs chain. It shows how to wire those tools together so each does the job it is best at.
Why combine tools
Each async tool covers only part of a requirement.
- Scheduled Apex answers "when". It runs at a set time, but its
executemethod runs in a single transaction with ordinary limits and cannot make synchronous callouts. - Batch Apex answers "how much". It processes millions of records in separate transactions, but it has no built-in clock.
- Queueable Apex answers "what next". It holds non-primitive state and can follow a batch with extra work.
A nightly cleanup job needs all three kinds of capability. The standard pattern is a thin scheduler that starts a batch. The batch does the heavy lifting. A Queueable job can run after the batch for follow-up work.
The core pattern: scheduler starts batch
The scheduler holds no business logic. It only starts the batch. This example reuses StaleLeadBatch from the Batch chapter.
public class NightlyStaleLeadJob implements Schedulable {
public void execute(SchedulableContext sc) {
Database.executeBatch(new StaleLeadBatch(), 200);
}
}
// Seconds Minutes Hours Day_of_month Month Day_of_week
String cron = '0 0 2 * * ?';
System.schedule('Nightly stale lead cleanup', cron, new NightlyStaleLeadJob());This split has three benefits.
- Limits. The scheduler's transaction does almost nothing, so it cannot hit a limit. The batch gets a fresh set of limits for every
executecall. - Reuse. You can run
StaleLeadBatchfrom the scheduler, from a button, or from anonymous Apex with the same code. - Testability. You test the batch logic on its own and test the scheduler only for wiring.
The scheduler is not the only way to start a batch later. System.scheduleBatch runs a batch once, a set number of minutes from now:
Id jobId = System.scheduleBatch(new StaleLeadBatch(), 'One-off stale lead run', 60, 200);The arguments are the batch instance, a job name, the delay in minutes, and the scope size. Use it for a one-time delayed run. Use System.schedule for anything recurring.
What can start what
Not every async context may start every other one. These rules cause many runtime errors, so check them before designing a chain.
| Running in | Start a batch | Enqueue a Queueable |
|---|---|---|
| Schedulable `execute` | Yes | Yes |
| Batch `start` or `execute` | No, throws an exception | Yes, one job per call |
| Batch `finish` | Yes | Yes |
| Queueable `execute` | Yes | Yes, one child job |
| Future method | No | Not recommended |
The important cell is "Batch execute, start a batch: No". If you want one batch to trigger another, do it in finish. A Queueable job can also start a batch, which is useful when a chain of Queueable steps ends in a large data operation.
Following a batch with a Queueable job
The finish method runs once after all execute calls complete. It is a good place to start follow-up work. A batch cannot make a callout unless it declares Database.AllowsCallouts, and that would make every execute call a callout transaction. A cleaner design lets the batch process data and hands the summary to a Queueable job that makes one callout.
public class StaleLeadReportJob implements Queueable, Database.AllowsCallouts {
private Integer processed;
public StaleLeadReportJob(Integer processed) {
this.processed = processed;
}
public void execute(QueueableContext ctx) {
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Partner_API/reports');
req.setMethod('POST');
req.setBody(JSON.serialize(new Map<String, Object>{ 'staleLeads' => processed }));
HttpResponse res = new Http().send(req);
System.debug('Report status: ' + res.getStatusCode());
}
}Change the batch's finish method to enqueue it:
public void finish(Database.BatchableContext bc) {
System.debug('Leads processed: ' + processed);
System.enqueueJob(new StaleLeadReportJob(processed));
}This works because StaleLeadBatch implements Database.Stateful. Without it, processed would reset to 0 for each execute call, and finish would see only the initial value.
The full flow looks like this:
Guarding against overlapping runs
The cron expression fires whether or not the previous run finished. If last night's batch is still processing at 02:00, a second StaleLeadBatch starts and both work on overlapping records. Two copies can also cause record lock errors.
Check for an active job before starting a new one:
public class NightlyStaleLeadJob implements Schedulable {
public void execute(SchedulableContext sc) {
Integer active = [
SELECT COUNT()
FROM AsyncApexJob
WHERE JobType = 'BatchApex'
AND ApexClass.Name = 'StaleLeadBatch'
AND Status IN ('Holding', 'Queued', 'Preparing', 'Processing')
];
if (active == 0) {
Database.executeBatch(new StaleLeadBatch(), 200);
} else {
System.debug('Skipping run: StaleLeadBatch is still active.');
}
}
}Skipping is a design choice. It suits a cleanup job, because the next night's run picks up the leftovers. If every run must happen, you could instead let the batch's finish method reschedule the next run with System.scheduleBatch. That removes overlap by construction, but a failure in finish stops the chain.
Limits to keep in mind
- An org can have at most 100 scheduled Apex jobs. Several scheduled jobs that each start a different batch count against this cap.
- A scheduler's
executemethod cannot make a synchronous callout. If the nightly work needs a callout, start a batch withDatabase.AllowsCalloutsor a Queueable job, and make the callout there. - You cannot change or delete an Apex class that has a pending scheduled job. Abort the job with
System.abortJob(cronTriggerId)first, then deploy, then schedule again. - The batch started by a scheduler runs with the permissions of the user who scheduled the job, not the user who triggered the clock. Rotating or deactivating that user can break the nightly run silently.
Testing the combination
Test the batch on its own first. Then test the scheduler for wiring. When you call System.schedule between Test.startTest and Test.stopTest, the job is created but does not fire until stopTest. Before then, the CronTrigger record shows zero runs:
@IsTest
private class NightlyStaleLeadJobTest {
@IsTest
static void schedulesNightlyRun() {
Test.startTest();
Id jobId = System.schedule(
'Test nightly stale lead cleanup',
'0 0 2 * * ?',
new NightlyStaleLeadJob()
);
CronTrigger ct = [
SELECT CronExpression, TimesTriggered
FROM CronTrigger
WHERE Id = :jobId
];
Assert.areEqual('0 0 2 * * ?', ct.CronExpression);
Assert.areEqual(0, ct.TimesTriggered);
Test.stopTest();
}
}This test checks that the job schedules with the right cron expression. It does not assert on lead changes, because a test cannot set LastModifiedDate to a past date, so no test lead would match the batch's query. Cover the batch logic in a test that calls Database.executeBatch between startTest and stopTest with records your query can match. For a testable design, you can pass the WHERE clause or a cutoff date into the batch constructor.
Choosing a combination
| Requirement | Combination |
|---|---|
| Recurring job over a large data set | Scheduled Apex starts Batch Apex |
| Recurring job over a small, known set that needs a callout | Scheduled Apex enqueues a Queueable job with `AllowsCallouts` |
| Large data job, then a summary callout | Batch `finish` enqueues a Queueable job |
| Several large jobs in order | Batch `finish` starts the next batch |
| One delayed run | `System.scheduleBatch` |
Exercise
A scheduled job's execute method calls Database.executeBatch, and the batch's execute method then tries to call Database.executeBatch for a second batch. What happens, and where should the second batch be started instead?
Show answer
The call inside the batch's execute method throws an exception, because a batch cannot be started from a batch's start or execute method. Start the second batch from the first batch's finish method, which is allowed.
Exercise
Your 02:00 scheduler starts a batch that sometimes takes more than 24 hours. What problem does this cause, and how do you prevent it?
Show answer
The next 02:00 run starts a second copy of the batch while the first is still running, so both can process the same records and cause lock errors. Query AsyncApexJob for the batch class with a status of Holding, Queued, Preparing, or Processing, and start a new batch only when none is found.