Invoke Batch Apex From Another Batch Apex

In batch class “Execute” method being called many times but “Start” and “Finish” method only once. So, To call another batch class from a batch class, we can call another batch class either in start method or in finish method as per our requirement.

Here in below example there are two batch classes “Batch1” and “Batch2“.
As per my requirement, I want to execute “Batch2” after finish the “Batch1“.
So, I’m calling “Batch2” class in “Batch1” finish method.

Batch1:

global class Batch1 implements Database.Batchable<Sobject>{

	//Method to get the data to be proceesed  
	global database.Querylocator Start(Database.BatchableContext bc){
		String query = 'Select Id, Name From Account Limit 1000';
		return Database.getQueryLocator(query);
	}


	//Method to execute the batch
	global void execute(Database.BatchableContext bc, Sobject[] scope){
		for(Sobject s : scope){ 
		Account a = (Account)s;
			// TO DO
			// add your logic 
		}
	}

	//Method to be called after the excute
	global void finish(Database.BatchableContext bc){
		//Add your start code for the other batch job here
		Database.executeBatch(new Batch2());
	}
}

Batch2:

global class Batch2 implements Database.Batchable<Sobject>{

	//Method to get the data to be proceesed  
	global database.Querylocator start(Database.BatchableContext bc){
		string query = 'Select Id, Name From Contact Limit 1000';
		return Database.getQueryLocator(query);
	}


	//Method to execute the batch
	global void execute(Database.BatchableContext bc, Sobject[] scope){
		for(Sobject s : scope){ 
		Contact c = (Contact)s;
			// TO DO
			// add your logic 
		}
	}

	//Method to be called after the excute
	global void finish(Database.BatchableContext bc){

	}
}

Leave a Reply