Tag Archives: Apex Batch Class

Invoke Batch Apex From Another Batch Apex

Only in batch class finish method, We can call another batch class. If you will call another batch class from batch class execute and start method, then Salesforce will throw below runtime error.

 
System.AsyncException: Database.executeBatch cannot be called from a batch start, batch execute, or future method.

Here in below example there are two batch classes “Batch1” and “Batch2“.
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){

	}
}

How to write batch apex class in Salesforce?

What is Batch Apex Class:

The class that implements Database.Batchable interface can be executed as a Batch Apex Class. Batch jobs can be programmatically invoked at runtime using Apex.

Batch Apex Governor Limits:

  • All methods in the class must be defined as global or public.
  • Up to five queued or active batch jobs are allowed for Apex.
  • A user can have up to 50 query cursors open at a time. For example, if 50 cursors are open and a client application still logged in as the same user attempts to open a new one, the oldest of the 50 cursors is released. Note that this limit is different for the batch Apexstart method, which can have up to 15 query cursors open at a time per user. The other batch Apex methods have the higher limit of 50 cursors.
  • Cursor limits for different Force.com features are tracked separately. For example, you can have 50 Apex query cursors, 50 batch cursors, and 50 Visualforce cursors open at the same time.
  • A maximum of 50 million records can be returned in the Database.QueryLocator object. If more than 50 million records are returned, the batch job is immediately terminated and marked as Failed.
  • If the start method returns a QueryLocator, the optional scope parameter of Database.executeBatch can have a maximum value of 2,000. If set to a higher value, Salesforce chunks the records returned by the QueryLocator into smaller batches of up to 2,000 records. If the start method returns an iterable, the scope parameter value has no upper limit; however, if you use a very high number, you may run into other limits.
  • If no size is specified with the optional scope parameter of Database.executeBatch, Salesforce chunks the records returned by the start method into batches of 200, and then passes each batch to the execute method.Apex governor limits are reset for each execution of execute.
  • The start, execute, and finish methods can implement up to 10 callouts each.
  • Batch executions are limited to 10 callouts per method execution.
  • The maximum number of batch executions is 250,000 per 24 hours.
  • Only one batch Apex job’s start method can run at a time in an organization. Batch jobs that haven’t started yet remain in the queue until they’re started. Note that this limit doesn’t cause any batch job to fail and execute methods of batch Apex jobs still run in parallel if more than one job is running.

Why we use Batch Class:

We use batch Apex to build complex DML operations for bulk records or long-running processes that run on thousands of records on the Force.com platform.
The Database.Batchable interface contains three methods that must be implemented.

start method:

global Database.QueryLocater start(Database.BatchableContext bc) {} 
  • The start method is called at the beginning of a batch Apex job.
  • This method is Used to collect the records or objects to pass to the interface method execute.
  • This method returns either a Database.QueryLocator object or an Iterable that contains the records or objects passed into the job.
  • Query executed in the start method will return maximum 5,00,00000 records in a transaction.

execute method:

global void execute(Database.BatchableContext bc , List scope) {} 
  • The execute method is called for each batch of records passed to the method.
  • This method is used for do all the processing for data.
  • This method takes the following:
    • A reference of Database.BatchableContext object.
    • A list of sObject records.
  • Batches of records are not guaranteed to execute in the order they are received from the start method.

finish method:

global void finish(Database.BatchableContext bc) {}
  • The finish method is called after all batches are processed.
  • This method is used to send confirmation emails or execute post-processing operations.
  • This method takes only one argument a reference of Database.BatchableContext object.
  • This method is called when all the batches are processed.

Each execution of a batch Apex job is considered a discrete transaction. For example, a batch Apex job that contains 1,000 records and is executed without the optional scope parameter from Database.executeBatch is considered five transactions of 200 records each. The Apex governor limits are reset for each transaction. If the first transaction succeeds but the second fails, the database updates made in the first transaction are not rolled back.

Here is an example of batch class.

Sample Code:

global class batchAccountUpdate implements Database.Batchable<sobject> {
 
    global Database.QueryLocator start(Database.BatchableContext bc){
     
        String query = 'SELECT Id, Name FROM Account';
        return Database.getQueryLocator(query);
    }
     
    global void execute(Database.BatchableContext bc, List<account> scope) {
     
        for(Account a : scope) {
            a.Name = a.Name + 'Updated';
        }
        update scope;
    } 
     
    global void finish(Database.BatchableContext bc) {
     
    }
}

If you want to notify admin on successful run, then in that case, create an email using this code below and send email by adding this code on finish method.

global void finish(Database.BatchableContext bc){
	Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
	mail.setToAddresses(new String[] {email});
	mail.setReplyTo('info@biswajeetsamal.com');
	mail.setSenderDisplayName('Account Batch Processing');
	mail.setSubject('Account Batch Process Completed');
	mail.setPlainTextBody('Account Batch Process has completed');
	Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
}

Call the Batch Class:

batchAccountUpdate batchAcc = new batchAccountUpdate();
database.executebatch(batchAcc, 10);

Note: If batch size is not mentioned the default batch size is 200 and the maximum batch size is 2000.