Chaining Batch Apex Classes

According to the Apex developer documentation there are a number of ways that Apex processes can be chained together. In this post I will explain two different methods by which you may chain multiple batchable interfaces together.

Consider the process flow scenario illustrated below:

The flows represented inside the yellow outline above signify a single batchable interface where we ultimately determine if it is alright to proceed to the next batchable interface or whether we need to re-process some previous batchable interface.

In the context of this example the finish method of the batchable interface is what's most relevant. We can perform some initial logic in the constructor or execute method and then check for the conditions to continue or re-process at the very end of the logic.

A simplified finish method for the batchable interface is below:

public void finish(Database.BatchableContext bc) {
	Boolean reprocessPreviousBatch = false; //Boolean designator for whether or not we should re-process a previous batch or chain to the next batch interface
	//check for conditions that permit continuation of logic flow
	//if conditions not met...
	//reprocessPreviousBatch = true;
	if (reprocessPreviousBatch == true) { //if we DO NOT meet the conditions to continue
		//daisy chain to a previous job
		previousBatchJob b = new previousBatchJob(); //construct a new previousBatchJob class
		Id jobId = System.scheduleBatch(b, 'Re-Process Job 1534731507', 1, 200); //schedules the previousBatchJob batch job to run one more time one minute from now - limit the batch size to 200
	} else { //otherwise, we do meet the conditions for chaining the next job
		//daisy chain to the next job
		nextBatchJob b = new nextBatchJob(); //construct a new nextBatchJob class	Database.executeBatch(b, 200); //execute the next job right now - limit the batch size to 200

The System.scheduleBatch method allows us to run a batchable interface a specified number of minutes in the future while the Database.executeBatch method allows us to run a batchable interface right now.

Automated Exchange Rates in

Reduce Repetitive Tasks, Eliminate Errors & Free Up Your Administrators.

Birthday Reminders for

It might lead to a sale. Or it might make you feel good.