Batch Class

Salesforce Batch Class

Ranbir Kumar Das
Salesforce Champion

--

Batch Apex is an asynchronous execution of Apex code, specially designed for processing a large number of records and has greater flexibility in governor limits than the synchronous code. As the name suggests, the batch word is used when you want to process a bulk amount of data effectively without any error that you need to apply some logic certainly.

The execution logic of the batch class is called once for each batch of records you are processing. Each time you invoke a batch class, the job is placed on the Apex job queue and is executed as a discrete transaction. This functionality has two awesome advantages:

  • Every transaction starts with a new set of governor limits, making it easier to ensure that your code stays within the governor execution limits.
  • If one batch fails to process successfully, all other successful batch transactions aren’t rolled back.
  • Most importantly, the interface can be scheduled to run batches at different time periods.

Governor Limits Defined for Batch Apex

Before you write batch apex code, you should focus on these governor limits for effective dealing with classes.

  • There is a maximum of five active or queued batch jobs are allowed for APEX.
  • At a particular time period, one user can open up to 50 query cursors. If the user attempts to open a new one the oldest 50 cursors will be released. Keep in mind that this limit is different for start method in the Batch APEX class that could have maximum five query cursors open at a particular time.
  • Other than start method, the rest of the methods have limit up to 50 cursors. This limit is tracked differently for multiple features in Force.com. For example, for a particular method, you could have 50 batch cursors, 50 Apex query cursors, and 50 VisualForce cursors open at the same time together.
  • For a database in the batch APEX, maximum of 50 million records can be returned at a particular time. Once all 50 million records are returned, the batch job will be terminated automatically and it is marked as the “Failure” in the end.
  • The default size for a record set in batch APEX is 200. The governor limits should always be redefined for each set of records as per the requirement.
  • When we are talking about the callouts then start, execute, and the finish methods are limited to ten callouts per method execution.
  • There is a limit set for hours as well. For example, you can execute a maximum number of 250,000 batch execution in 24 hours.
  • At one time, only one start method will run for an organization. The batch jobs that are not started yet will stay in queue until they are not started. Keep in mind that this limit will not set any batch job to failure or it will not stop the execution of any batch APEX jobs but running in parallel if there is more than one job scheduled in the batch.

To write a batch APEX class, you should first implement the “Database.Batchable” interface in the Salesforce and including the execution of these three methods.

  • Start
  • Execute
  • Finish

Create an apex class that implements Database. Batchable interface and class can be global or public as mentioned below.

global class batchExample implements Database.Batchable<sObject> {}.We have to create a global apex class which extends Database.Batchable Interface because of which the salesforce compiler will know, this class incorporates batch jobs.

What is the difference between database.batchable and database.batchableContext

Database.batchable is an interface.
Database.batchableContext is a context variable which store the runtime information (jobId etc.)

Start: This method is used to collect objects or records that need to be passed to an interface method for processing. This method is called at the beginning when Batch apex starts to execute. In most of the cases, the “QueryLocator” method is used to play with the simple SOQL query and to generate the scope of objects within a batch job.

global Database.QueryLocator start(Database.BatchableContext BC) {
String query = ‘SELECT Id,Name FROM Account’;
return Database.getQueryLocator(query);
}

Consider the following points to understand the method −

  • Use the Database.QueryLocator object when you are using a simple query to generate the scope of objects used in the batch job. In this case, the SOQL data row limit will be bypassed.

Execute: This method will perform the actual processing for each batch or chunk where data needs to be passed with the help of a method. The default size defined for each batch is 200 records maximum. If the size of the record set is larger, break it down into manageable pieces first before you execute them. If the size is not defined well then records will not be executed in the same order as they were received by start method.

global void execute(Database.BatchableContext BC, List<Account> scope) {
for(Account a : scope) {
a.Name = a.Name + ‘Batch-Execute’;
}
update scope;
}

where List<Account> is returned by the Database.QueryLocator method.This method gets called after the Start method and does all the processing required for Batch Job.

Finish:This method is responsible to perform post-processing operation like email sending or more once all batches are executed successfully. Here is the basic syntax of a batch APEX class how are they written in the Salesforce.

global void finish(Database.BatchableContext BC) {

// Below code will fetch the job Id

AsyncApexJob a = [Select a.TotalJobItems, a.Status, a.NumberOfErrors,

a.JobType, a.JobItemsProcessed, a.ExtendedStatus, a.CreatedById,

a.CompletedDate From AsyncApexJob a WHERE id = :BC.getJobId()];

// get the job Id

System.debug('$$$ Jobid is'+BC.getJobId());

}

How to execute your Batch Class?

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 + '******';}update scope;}global void finish(Database.BatchableContext BC) {}}//----------Execute your batch class
batchAccountUpdate obj=new batchAccountUpdate();
Database.executeBatch(obj);

To check your Batch job go to the Setup and click on the Apex Job.you will get all the batch related process.

--

--

Ranbir Kumar Das
Salesforce Champion

I M Believer, Helper, Chaser, Thinker, Rich, Explorer, Prayer, Boss, Freedom, Fearless, Investor, Faith, Creator, trillionaire, CSM, Salesforce certified