Sub topic 10
Combining the tools: a scheduler that starts a batch
This chapter assumes you can write a Batch class with start, execute, and finish, and a Schedulable class. It also assumes you know what a cron expression is. Here you will connect those pieces into one pipeline.
Why combine tools
Each async tool covers a gap in the others.
- Batch Apex handles large volumes, but it cannot start itself.
- Scheduled Apex starts on a clock, but its
executemethod runs in a normal transaction with normal limits. - Queueable Apex is a light follow-up step with no query-locator machinery.
The most common pairing is a scheduler that does nothing except launch a batch. The scheduler stays small, and the batch does the heavy work in separate transactions.
The scheduler-starts-batch pattern
This is the pattern from the earlier chapters. The scheduled class has one job, which is to call Database.executeBatch.
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());The cron string runs the job every day at 02:00. The scheduler's own transaction ends almost immediately after it queues the batch. The batch then runs its start, execute, and finish calls as separate async transactions.
Adding a Queueable follow-up in finish
The finish method runs once, after the last execute call. It is a good place to start a Queueable job, for example to send a summary or begin a second phase. The batch must be Database.Stateful so that the counter survives between execute calls.
public class StaleLeadSummaryJob implements Queueable {
private Integer processed;
public StaleLeadSummaryJob(Integer processed) {
this.processed = processed;
}
public void execute(QueueableContext ctx) {
System.debug('Stale leads marked: ' + processed);
}
}
public class StaleLeadReportingBatch implements Database.Batchable<SObject>, Database.Stateful {
private Integer processed = 0;
public Database.QueryLocator start(Database.BatchableContext bc) {
return Database.getQueryLocator([
SELECT Id, Description FROM Lead
WHERE IsConverted = false AND LastModifiedDate < LAST_N_DAYS:365
]);
}
public void execute(Database.BatchableContext bc, List<Lead> scope) {
for (Lead l : scope) {
l.Description = 'Stale';
}
update scope;
processed += scope.size();
}
public void finish(Database.BatchableContext bc) {
System.enqueueJob(new StaleLeadSummaryJob(processed));
}
}The Queueable class carries the count in a member variable. That is the reason to use Queueable here, because a future method could not accept it as a non-primitive argument if you later pass richer data.
Rules that affect the combination
- A scheduler can call
Database.executeBatchandSystem.enqueueJob. It cannot do large processing itself. - Do not schedule a job that schedules itself every minute to poll for work. A batch's
finishcan start the next batch instead, which gives sequential runs without polling. - If five batch jobs are already active, a new
executeBatchcall goes to the flex queue in Holding status. The call does not fail. The job still runs, but later than the scheduled time. - An org can hold only 100 scheduled Apex jobs. One scheduler per pipeline keeps you well under that.
Testing the pipeline
Test each stage separately. Run the batch with Test.startTest and Test.stopTest, and assert on the data. Test the scheduler by calling System.schedule between those two calls. The scheduled job is executed when stopTest runs, but a batch started from it may need its own check. Keep the scheduler test small and put detailed assertions in the batch test.
Exercise
A nightly job must update about 2 million records and then email a count. Which tools do you combine, and which class holds the counter?
Show answer
Use a Schedulable class to start a Batch class at the desired time. The batch implements Database.Stateful and keeps the counter in a member variable, and its finish method enqueues a Queueable (or sends the email) with that count.