Sub topic 15
Chaining Jobs from finish
This chapter assumes you can write a Database.Batchable class with start, execute and finish methods, start it with Database.executeBatch, and read the AsyncApexJob record. It covers how to start one batch job from the finish method of another, what limits apply, and how to avoid the common mistakes.
Why chain jobs
Some processes have steps that must run in order. For example, you may need to rate accounts first, then clean up the contacts that belong to them. The second step depends on the data the first step wrote. If you start both jobs at the same time, the second one may read records before the first one has changed them.
Chaining solves this. The finish method runs once, after every execute call has completed. If finish calls Database.executeBatch, the next job is queued only when the first job has processed all of its records.
public void finish(Database.BatchableContext bc) {
// Start the next job only after this one has completed
Database.executeBatch(new ContactCleanupBatch(), 200);
}The call returns the Id of the new AsyncApexJob. The new job gets its own start, execute and finish cycle, its own batch size, and fresh governor limits.
How a chain runs
Job B does not start inside Job A's finish transaction. The call only adds Job B to the queue. Job A's finish then ends, and Job B starts when the platform has a free slot for it.
Limits that apply to chaining
The finish method is a normal transaction with its own limits. These rules matter for chains:
- Queue slots. A job started from finish counts toward the same queue limits as any other job. Up to five batch jobs can be queued or active at once. If those slots are full, a job started with Database.executeBatch goes into the Flex Queue, which holds up to 100 jobs in the Holding status. Check the current limits in the Salesforce documentation for your org, because they can change between releases.
- One start per transaction in finish. You can call Database.executeBatch from finish. The limit on starting batch jobs applies to the transaction, so do not try to start many jobs in a loop from one finish method.
- No parallel guarantee. Chaining gives you order, not speed. Job B waits for Job A to finish completely.
- Test context. In a test, a call to Database.executeBatch from finish is not allowed. Salesforce raises an error if a test tries to chain from finish, so you must guard the call (see below).
Passing information to the next job
The next job is a new object. It does not share fields with the first one. If it needs data from the first job, pass it through the constructor.
public class AccountRatingBatch implements Database.Batchable<SObject>, Database.Stateful {
public Set<Id> updatedIds = new Set<Id>();
public Database.QueryLocator start(Database.BatchableContext bc) {
return Database.getQueryLocator([
SELECT Id, Rating FROM Account WHERE Rating = null
]);
}
public void execute(Database.BatchableContext bc, List<Account> scope) {
for (Account a : scope) {
a.Rating = 'Cold';
}
List<Database.SaveResult> results = Database.update(scope, false);
for (Integer i = 0; i < results.size(); i++) {
if (results[i].isSuccess()) {
updatedIds.add(scope[i].Id);
}
}
}
public void finish(Database.BatchableContext bc) {
if (!updatedIds.isEmpty()) {
Database.executeBatch(new ContactCleanupBatch(updatedIds), 200);
}
}
}public class ContactCleanupBatch implements Database.Batchable<SObject> {
private Set<Id> accountIds;
public ContactCleanupBatch(Set<Id> accountIds) {
this.accountIds = accountIds;
}
public Database.QueryLocator start(Database.BatchableContext bc) {
return Database.getQueryLocator([
SELECT Id, Description FROM Contact WHERE AccountId IN :accountIds
]);
}
public void execute(Database.BatchableContext bc, List<Contact> scope) {
for (Contact c : scope) {
c.Description = null;
}
update scope;
}
public void finish(Database.BatchableContext bc) {
System.debug('Contact cleanup finished: ' + bc.getJobId());
}
}Database.Stateful lets the first job collect the Ids across execute calls. This approach has a cost. The state is serialized between chunks, and a large Set of Ids makes every chunk slower. A set holding millions of Ids can also hit heap limits, and a SOQL IN clause with a very large set is not a good fit. For high volumes, pass a marker instead of the data. For example, write a flag or a run identifier on the records in the first job, and have the second job query on that field.
Guarding against test failures
Salesforce does not let a test start a batch job from finish. Wrap the chain call in a check so the class still passes tests.
public void finish(Database.BatchableContext bc) {
if (!Test.isRunningTest()) {
Database.executeBatch(new ContactCleanupBatch(), 200);
}
}This means the chaining line is not covered by a test. Keep the finish method small so that the untested part is only the one call. Test the second batch class on its own, in a separate test method.
Common errors
| Problem | Cause | Fix |
|---|---|---|
| Next job never starts | An unhandled exception in finish before the executeBatch call | Keep work before the call minimal and wrap risky code in try/catch |
| Chain stops after a failed chunk | Code assumes success and skips the call | Decide whether failures should stop the chain, and check NumberOfErrors on the AsyncApexJob |
| Error when testing | Chaining from finish in a test context | Guard with Test.isRunningTest() |
| Job B reads old data | Both jobs were started from the same place instead of chained | Start Job B only from Job A's finish |
| Chain runs forever | A job starts itself again with no end condition | Add a stop condition, such as a query that returns no records |
| Heap errors in finish | Large state carried through Database.Stateful | Pass a marker field instead of large collections |
Deciding whether the chain should continue
A failed record in one chunk does not stop the job. The finish method still runs once all chunks have been attempted, even if some chunks failed. Your code must decide what to do when errors occurred. You can read the job record and decide.
public void finish(Database.BatchableContext bc) {
AsyncApexJob job = [
SELECT Status, NumberOfErrors
FROM AsyncApexJob
WHERE Id = :bc.getJobId()
];
if (job.NumberOfErrors == 0) {
Database.executeBatch(new ContactCleanupBatch(), 200);
} else {
System.debug('Chain stopped. Errors: ' + job.NumberOfErrors);
}
}If you use Database.update with allOrNone set to false, as in the earlier chapter on partial failures, record-level failures do not raise exceptions. In that case NumberOfErrors stays at zero, so count the failures in your own Stateful field and test that field instead.
Self-chaining loops
A job can start a new instance of itself from finish. This is useful when each run handles a limited number of records, for example one that must stay under a daily callout allowance. It is risky, because a mistake leaves a job that never ends.
public void finish(Database.BatchableContext bc) {
Integer remaining = [SELECT COUNT() FROM Account WHERE Rating = null LIMIT 1];
if (remaining > 0 && failed == 0) {
Database.executeBatch(new AccountRatingBatch(), 200);
}
}Stopping on any failure, as shown with the failed counter, prevents a loop where the same bad record is retried forever. Without that check, a record that always fails stays in the query results and the job restarts without end.
Alternatives to chaining
Chaining from finish is simple, but it ties the steps together in code. Consider other options when:
- Steps are unrelated. Run them as separate jobs, each with its own schedule.
- You need a fixed time for each step. Use Schedulable classes.
- A step is small. A Queueable job can be a lighter second stage than a full batch.
Exercise
A batch job runs Database.update(scope, false) in execute and counts failed records in a Stateful field called failed. In finish, you want to start a cleanup job only if no record failed. Why is checking AsyncApexJob.NumberOfErrors alone not enough?
Show answer
Database.update with allOrNone set to false does not throw an exception for a failed record, so the platform does not count it as a batch error. NumberOfErrors can stay at 0 even when records failed. Check your own failed counter, and optionally NumberOfErrors as well, before calling Database.executeBatch.
Exercise
Why does a test fail if finish calls Database.executeBatch, and how do you keep the class testable?
Show answer
Salesforce does not allow a test to chain a batch job from finish. Wrap the call in if (!Test.isRunningTest()) and test the second batch class separately.