Sub topic 2
Chaining Queueable Jobs and Scheduling Large-Volume Work
Assume you know Apex classes, SOQL, DML, governor limits, triggers, and basic tests. This chapter focuses on selecting and combining asynchronous tools.
Chaining Queueable Jobs
A Queueable job can enqueue one child Queueable job from its execute method. This supports sequential steps while keeping each step in a separate transaction.
public class ProcessAccounts implements Queueable {
private List<Id> accountIds;
public ProcessAccounts(List<Id> accountIds) {
this.accountIds = accountIds;
}
public void execute(QueueableContext context) {
List<Account> accounts = [
SELECT Id, Description
FROM Account
WHERE Id IN :accountIds
];
for (Account account : accounts) {
account.Description = 'Processed';
}
update accounts;
if (!accountIds.isEmpty()) {
System.enqueueJob(new NotifyPartner(accountIds));
}
}
}A chain is useful when step two must wait for step one. Keep chains finite, and remember that each job has separate limits.
Finalizers for Failure Handling
A transaction finalizer runs after a Queueable transaction finishes. It can inspect success or failure, write a log, or enqueue a retry.
public class JobFinalizer implements Finalizer {
public void execute(FinalizerContext context) {
if (context.getResult() == ParentJobResult.UNHANDLED_EXCEPTION) {
System.debug(LoggingLevel.ERROR,
context.getException().getMessage());
}
}
}Attach it inside execute with System.attachFinalizer(...). A finalizer is a recovery mechanism, not a replacement for validation and proper error handling.
Batch Apex for Large Data Volumes
Batch Apex divides a query result into scopes. start finds records, execute processes one scope, and finish performs final work.
public class StaleLeadBatch
implements Database.Batchable<SObject> {
public Database.QueryLocator start(Database.BatchableContext context) {
return Database.getQueryLocator([
SELECT Id, Description FROM Lead
WHERE IsConverted = false
]);
}
public void execute(
Database.BatchableContext context,
List<Lead> scope
) {
for (Lead lead : scope) {
lead.Description = 'Stale';
}
update scope;
}
public void finish(Database.BatchableContext context) {
System.debug('Batch complete');
}
}Scope Size and State
Pass the scope size when starting a batch:
Database.executeBatch(new StaleLeadBatch(), 200);Smaller scopes reduce per-transaction pressure but create more transactions. Larger scopes improve throughput when each record is cheap. Add Database.Stateful when member variables, such as a processed counter, must persist between execute calls.
Scheduled Apex
Scheduled Apex starts code at a chosen time. It commonly launches a batch job rather than processing records directly.
public class NightlyLeadSchedule implements Schedulable {
public void execute(SchedulableContext context) {
Database.executeBatch(new StaleLeadBatch(), 200);
}
}
String cron = '0 0 2 * * ?';
System.schedule('Nightly lead cleanup', cron,
new NightlyLeadSchedule());The expression means seconds, minutes, hours, day of month, month, and day of week. This schedule runs daily at 02:00 in the scheduling user's time zone.
Exercise
Which tool fits a nightly process that must handle millions of records in manageable transactions?
Show answer
Scheduled Apex should launch a Batch Apex job. The scheduler controls when it starts, and Batch Apex controls how records are divided.