Executing Batch Apex Classes in Sequence

According to the Apex developer documentation, there are various ways to chain together Apex processes. In this post, I will elucidate two distinct methods for chaining multiple batchable interfaces.

Let’s contemplate the process flow scenario outlined below:

The processes enclosed within the yellow outline above represent a singular batchable interface. Here, we make the ultimate decision on whether to proceed to the next batchable interface or re-process some previous batchable interface.

In this example, the finish method of the batchable interface holds particular significance. Initial logic can be executed in the constructor or execute method, and the conditions to continue or re-process can be checked at the conclusion of the logic.

A streamlined finish method for the batchable interface is as follows:

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 1705484397', 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 enables the execution of a batchable interface after a specified number of minutes in the future, whereas the Database.executeBatch method facilitates the immediate execution of a batchable interface.