Sub topic 3
Combining Scheduled, Batch, and Queueable Apex
Assume you know basic Apex, SOQL, DML, and unit testing. A scheduler decides when work starts. A batch job processes many records in separate transactions. A Queueable job handles smaller, stateful work.
A scheduler that starts a batch
Keep scheduling separate from processing. The scheduled class should start the batch and return quickly.
public class NightlyStaleLeadJob implements Schedulable {
public void execute(SchedulableContext context) {
Database.executeBatch(new StaleLeadBatch(), 200);
}
}
String cron = '0 0 2 * * ?';
System.schedule(
'Nightly stale lead cleanup',
cron,
new NightlyStaleLeadJob()
);The scope size, 200, controls how many records each batch transaction receives. Each transaction gets its own governor limits.
Testing async Apex
Use Test.startTest() and Test.stopTest() around the scheduling call. Test.stopTest() forces queued asynchronous work to run before assertions.
@IsTest
private class NightlyStaleLeadJobTest {
@IsTest
static void runsScheduledBatch() {
Test.startTest();
String jobId = System.schedule(
'Test stale lead cleanup',
'0 0 2 1 1 ? 2099',
new NightlyStaleLeadJob()
);
Test.stopTest();
CronTrigger result = [
SELECT State
FROM CronTrigger
WHERE Id = :jobId
];
Assert.areEqual('COMPLETE', result.State);
}
}Monitoring async jobs
Use the Apex Jobs page for a quick view. Code can query AsyncApexJob when it has a batch or Queueable job ID.
AsyncApexJob job = [
SELECT Status, JobItemsProcessed, TotalJobItems, NumberOfErrors
FROM AsyncApexJob
WHERE Id = :batchId
];Status, processed counts, and errors help distinguish a slow job from a failed job.
Choosing the right tool
| Requirement | Best starting point |
|---|---|
| Run once later with simple inputs | Future method |
| Hold state or chain steps | Queueable Apex |
| Process a large query result | Batch Apex |
| Start work at a specific time | Scheduled Apex |
Combine tools when each has a clear role, such as Scheduled Apex starting Batch Apex.
Common pitfalls and anti-patterns
- Do not use Batch Apex for a few records.
- Do not schedule many overlapping batches.
- Do not assume asynchronous execution is immediate.
- Do not enqueue unlimited child jobs from a Queueable job.
- Do not omit assertions about the final data state in async tests.
Exercise
Which combination should process all stale leads every night?
Show answer
Use Scheduled Apex to start a Batch Apex job, then monitor the batch through AsyncApexJob or the Apex Jobs page.