How can you trigger subsequent asynchronous jobs inside the finish method of a Batch Apex class?
Answer
Basics: finish() runs once after the last chunk. It is where you send summary emails and start the next stage of a multi-step pipeline (for example load, then recalculate, then notify).
How it works:
- Batch A runs all
execute()chunks. finish()inspects the job (AsyncApexJobviabc.getJobId()) to see whether errors occurred.- If acceptable, it calls
Database.executeBatch(new BatchB(), size)or enqueues a queueable. - B starts when a slot is available (it may wait in the Flex Queue).
Advanced / deep dive: finish() runs even if some chunks failed, so check NumberOfErrors before continuing. Pass results forward through the next job's constructor or through Database.Stateful fields. Chained batch jobs are independent jobs: no shared transaction, no automatic rollback. Production chains can be infinite, which is useful for polling loops but dangerous without an exit condition; in Developer Edition the queueable chain depth is 5. For parallel work, start several jobs from finish(), remembering the 5-active and 100-Holding limits. For orchestrating many steps with retries, consider a queueable-based state machine with a Finalizer or a custom "pipeline" record that tracks step status.
Code / config example:
public void finish(Database.BatchableContext bc) {
AsyncApexJob job [
SELECT Status, NumberOfErrors, JobItemsProcessed, TotalJobItems
FROM AsyncApexJob :bc.getJobId()
];
(job.NumberOfErrors == ) {
Database.executeBatch( (), );
} {
System.debug(LoggingLevel.ERROR, + job.NumberOfErrors + );
}
}