Sub topic 15
Chaining jobs from finish
This chapter assumes you can write a Database.Batchable class with start, execute and finish methods. It also assumes you know what a job queue is and what governor limits are.
Why chain jobs
Some work has to happen in order. You might rate accounts first, then clean up their contacts. If both jobs are started at the same time, the second may read data the first has not changed yet.
Chaining solves this. The finish method runs once, after every execute call of the current job has completed. If finish starts the next job, the second job begins only after the first one is done.
public void finish(Database.BatchableContext bc) {
// Start the next job only after this one has completed
Database.executeBatch(new ContactCleanupBatch(), 200);
}Database.executeBatch returns the Id of the new job. The new job enters the queue like any other job. It may wait if other jobs are ahead of it.
Passing information to the next job
The next job is a new object. It does not see the fields of the first one. Pass what it needs through its constructor. If the first class implements Database.Stateful, finish can read the counters it collected.
public class ContactCleanupBatch implements Database.Batchable<SObject> {
private Integer previousFailures;
public ContactCleanupBatch(Integer previousFailures) {
this.previousFailures = previousFailures;
}
public Database.QueryLocator start(Database.BatchableContext bc) {
return Database.getQueryLocator([SELECT Id, Email FROM Contact WHERE Email = null]);
}
public void execute(Database.BatchableContext bc, List<Contact> scope) {
// clean up contacts here
}
public void finish(Database.BatchableContext bc) {
System.debug('Previous job had ' + previousFailures + ' failures.');
}
}In the first job's finish, you would call new ContactCleanupBatch(failed).
Deciding whether to continue
finish is a normal method, so you can add conditions. A common pattern is to check the job record and start the next job only if the first one went well.
public void finish(Database.BatchableContext bc) {
AsyncApexJob job = [
SELECT Status, NumberOfErrors FROM AsyncApexJob WHERE Id = :bc.getJobId()
];
if (job.Status == 'Completed' && job.NumberOfErrors == 0) {
Database.executeBatch(new ContactCleanupBatch(0), 200);
}
}Common errors
- Chaining from
execute. Do not callDatabase.executeBatchfromexecute. Salesforce does not allow a batch job to start another batch job from there. Usefinish. - Endless loops. If job A chains to B and B chains back to A, the chain never ends. Add a stop condition, such as a counter passed through the constructor.
- Assuming
finishalways runs. If a job is aborted, orstartfails,finishmay not behave as you expect. Check the job status before you rely on the chain. - Putting too much in
finish. It runs in one transaction with normal limits. Keep it short. - Tests. In a test,
finishcan run, but a chainedDatabase.executeBatchcall fromfinishis not run. Test the chained job separately.
Exercise
Why should the second job be started from finish and not from execute?
Show answer
finish runs once, after all chunks of the first job have been processed, so the second job sees the finished data. Salesforce also does not allow a batch job to start another batch job from execute, and doing so would try to start one job per chunk.
Exercise
How can the second job in a chain use the failure count collected by the first job?
Show answer
Make the first class implement Database.Stateful to keep the counter between chunks. Then, in finish, pass the value to the second job's constructor, for example new ContactCleanupBatch(failed).