Introduction to Batch Apex Salesforce

on

|

views

and

comments

Table of Contents

Introduction

Batch apex is used to process the large no of data in Asynchronous mode.( Runs when the resources are free )

With the help of batch apex we can process upto 50 million records.

We prefer to use the batch apex when we have large set of data and we wanted to perform/execute certain logic on the scheduled basis.

For Example, You are working for a telecom industry and you need to send the Email/SMS to all the mobile subscribers whose topup is going to expire in next 7 & 3 days.

Note:- Batch Apex is nothing but it is an Apex Class which is implementing an Interface provided by Salesforce

Implementing the Database.Batchable Interface

To make any class work as Batch Class you need to implement an interface Batchable which is inside Database namespace. See below example

				
					public class BatchExample implements Database.Batchable<sObject>{
}
				
			

Batchable interface have 3 main pre-defined methods which you must need to implement and those methods are

  1. start
  2. execute
  3. finish

Start Method – This is the first method of batch apex which always executes once not more than once. This method is responsible for returning the List which will be passed inside execute method.

Note:- This method will always execute.

				
					public (Database.QueryLocator | Iterable<sObject>) start(Database.BatchableContext bc) {}
				
			

Execute Method – To do the required processing for each chunk of data, use the execute method. This method is called for each batch of records that you pass to it.

This method takes the following:

  1. A reference to the Database.BatchableContext object.
  2. A list of sObjects, such as List, or a list of parameterized types. 

Note: – This method can be executed many times depends upon no of records returned by start method and batch size of the batch apex.

				
					public void execute(Database.BatchableContext batchContext, List<sObject> scope){}
				
			

Finish Method Always executes once after all the execute chunks has been executed. In this method you can have logic to send the email, call another batch apex.

				
					public void finish(Database.BatchableContext BC){}
				
			

Database.BatchableContext

You might have noticed that Database.BatchableContext is being used in all three methods of batch apex. So with the help of Database.BatchableContext class we can track the state of the batch apex.

We can also abort the batch apex and prevent the logic from being executed.

The class have following methods

  1. getJobId – Returns the ID of the batch Job.
  2. getChildJobId – Returns the ID of the current batch job chunk that is being processed. The id of the execute chunk

Database.QueryLocator in start method

As you might have seen that start method have 2 return type and one is Database.QueryLocator. 

This is the most widely return type used in batch apex and when we use Database.QueryLocator as return type then we use Database.getQueryLocatior method to execute the SOQL query and return the records/scope.

				
					public Database.QueryLocator start(Database.BatchableContext BC){
      return Database.getQueryLocator('SELECT Id, Name FROM Account WHERE Industry <> null LIMIT 500000');
   }
				
			

Batch Apex Structure

Below is the Sample structure of the batch apex without any logic.

				
					public class UpdateAccountFields implements Database.Batchable<sObject>{

    public Database.QueryLocator start(Database.BatchableContext BC){
      return Database.getQueryLocator('SELECT Id, Name FROM Account');
    }

    public void execute(Database.BatchableContext BC, List<Account> scope){
      
    }

    public void finish(Database.BatchableContext BC) {
		
    }
}
				
			

Batch Apex Example

Below is a simple batch apex which is making a query on account object and updating the account name.

				
					public class UpdateAccountFields implements Database.Batchable<sObject>{

   public Database.QueryLocator start(Database.BatchableContext BC){
      return Database.getQueryLocator('SELECT Id, Name FROM Account');
   }

   public void execute(Database.BatchableContext BC, List<Account> scope){
      for(Account a : scope){
		  a.Name = a.Name+' Updated Batch';
      }
	  update scope;
   }

   public void finish(Database.BatchableContext BC){

   }

}
				
			

Use Finish Method in Example

As we have read that finish method executes once and can be used to Send the Email or Execute another batch apex. So we will modify the finish method to send the email to yourself stating that batch apex has been completed.

Find the complete code below

				
					public class UpdateAccountFields implements Database.Batchable<sObject>{

   public Database.QueryLocator start(Database.BatchableContext BC){
      return Database.getQueryLocator('SELECT Id, Name FROM Account');
   }

   public void execute(Database.BatchableContext BC, List<Account> scope){
      for(Account a : scope){
		  a.Name = a.Name+' Updated Batch';
      }
	  update scope;
   }

   public void finish(Database.BatchableContext BC) {
		Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
		String email = 'youremail@gmail.com';
		mail.setToAddresses(new String[] {
			email
		});
		mail.setReplyTo('youremail@gmail.com');
		mail.setSenderDisplayName('Batch Processing');
		mail.setSubject('Batch Process Completed');
		mail.setPlainTextBody('UpdateAccountFields Batch Process has completed');

		Messaging.sendEmail(new Messaging.SingleEmailMessage[] {
			mail
		});
	}

}
				
			

Execute Batch apex

When you have completed the development. Now, the time is to execute the batch apex and text it.

To execute the batch apex we use Database.executeBatch method which accept the instance of batch class and batch size as parameters.

See below code to execute the above batch apex.

				
					UpdateAccountFields batch = new UpdateAccountFields()
ID batchprocessid = Database.executeBatch(batch);
/* Query the AsyncApexJob to get the batch Status */
AsyncApexJob aaj = [SELECT Id, Status, JobItemsProcessed, TotalJobItems, NumberOfErrors 
                    FROM AsyncApexJob WHERE ID =: batchprocessid ];
				
			

Batch Job Status

  • Holding – Job has been submitted and is held in the Apex flex queue until system resources become available to queue the job for processing.
  • Queued – Job is awaiting execution.
  • Preparing – The start method of the job has been invoked. This status can last a few minutes depending on the size of the batch of records.
  • Processing – Job is being processed.
  • Aborted – Job aborted by a user.
  • Completed – Job completed with or without failures.
  • Failed – Job experienced a system failure.

Resources

Amit Singh
Amit Singhhttps://www.pantherschools.com/
Amit Singh aka @sfdcpanther/pantherschools, a Salesforce Technical Architect, Consultant with over 8+ years of experience in Salesforce technology. 21x Certified. Blogger, Speaker, and Instructor. DevSecOps Champion
Share this

Leave a review

Excellent

SUBSCRIBE-US

Book a 1:1 Call

Must-read

How to Utilize Salesforce CLI sf (v2)

The Salesforce CLI is not just a tool; it’s the cornerstone of development on the Salesforce Platform. It’s your go-to for building, testing, deploying, and more. As one of the most important development tools in our ecosystem

Save the day of a Developer with Apex Log Analyzer

Table of Contents What is Apex Log Analyzer? Apex Log Analyzer, a tool designed with Salesforce developers in mind, is here to simplify and accelerate your...

Salesforce PodCast

Introduction Hey Everyone, Welcome to my podcast, the first-ever podcast in India for Salesforce professionals. Achievement We are happy to announce that we have been selected as Top...

Recent articles

More like this

1 COMMENT

LEAVE A REPLY

Please enter your comment!
Please enter your name here

5/5

Stuck in coding limbo?

Our courses unlock your tech potential