Batch Apex

salesforce data migration services

Batch Apex

Posted by Srivalli T

In this blog we will learn how to use Batch Apex. It is used to run large jobs (think thousands or millions of records) that would exceed normal processing limits. Each time you invoke a batch class, the job is placed on the Apex job queue and is executed as a discrete transaction.
Definition: Batch Apex allows you to define a single job that can be broken up into manageable chunks,where every chunk can be processed separately.
When will we go to Batch Apex: Let’s take an example – In your org, there are more than 10,000 records in Account Object. If you need to make a field update on every record on Account Object, then we have governor limits that restrict us from achieving this task.  In a single transaction we can process only 10000 records. Then in this case where there are more than 10,000 records in the organization, we can not perform this Field update.
To write Batch Apex class, your class must implement the Database.Batchable interface and it includes the following three methods
1.Start()—- it will execute only once.
2.Execute()—–How many times this method will execute is based on the batch size and records
3.Finish()—-it will execute only once.

  1. Start()

❖ This method is called at the beginning of the Batch Apex job.
❖ This will collect the records of the object on which you want to perform the operation.
❖These records are broken down into subtasks and given that into execute method.
Syntax: global (Database.QueryLocator/ Iterable) start(Database.BatchableContext bc)
The return type of Start method can be Database.QueryLocator or Iterable<Sobject>

  1. Execute()

❖The records which are fetched from the Start method are divided into batches of 200 records each.
❖Every batch of 200 records are separately passed to the execute method and the operation what we want to perform on these records are written in this Execute method.
Syntax:Global void execute (Database.BatchableContext BC,List)

  1. Finish()

❖When the start method has fetched 1000 records on which we want to perform the operation they are divided into 5 batches of size 200.
❖On every batch, execute method is called. After every batch the governor limits are reset for the execute method.
❖Once all the batches are executed then finish method will be called to send email notification or post execution work.
Syntax:Global void execute (Database.BatchableContext BC,List)
Example Program

Scenario: Create Custom object ‘Custom Product’. Create fields in the Custom Product

And create custom fields in Product
There are two Objects
1)Product (standard Object)
2)Custom Product
Maintain both objects field ‘product_code’ as similar. For example standard Product ProductCode =IN-7010 and Custom Product Product_Code__c=IN-7010
When Custom Product’s Expiry_Date_Custom__c is less than today, then add the Prod_customer_Quantity__c into Prod_Standard_Quantity__c and delete the custom product.

global class BatchapexproductUpdate implements Database.Batchable<sObject>,Database.Stateful{
public Map<String,Custom_Product__c> cusExpiryProdMap; public List<Custom_Product__c> custProdTodelete; public Map<String,Product2> standMap; public List<Product2> updateStdProdList; public List<Product2> producttoUpdateList;
                      global Database.QueryLocator Start(Database.BatchableContext bc){
                                return Database.getQueryLocator([select id,Expiry_Date_Custom__c,Price__c,Prod_customer_Quantity__ c,Product_Code__c from Custom_Product__c
                                where Expiry_Date_Custom__c < Today]);
} global void execute(Database.BatchableContext bc,List<Custom_Product__c> scope){
                      cusExpiryProdMap= new Map<String,Custom_Product__c>();
custProdTodelete= new List<Custom_Product__c>();
for(Custom_Product__c cus:scope){
                      } } global void finish(Database.BatchableContext bc){
standMap= new Map<String,Product2>(); updateStdProdList = new List<Product2>(); producttoUpdateList= new List<Product2>(); producttoUpdateList=[select id,Name,ProductCode,Prod_Standard_Quantity__c,Standard_Pri ce__c from Product2
where ProductCode IN:cusExpiryProdMap.keyset()];
                                for(Product2 prd:producttoUpdateList){ standMap.put(prd.ProductCode,prd); }
                      for(String prod:standMap.keyset()){ standMap.get(prod).Prod_Standard_Quantity__c=standMap.get( prod).Prod_Standard_Quantity__c+cusMap.get(prod).Prod_cust omer_Quantity__c;
                      updateStdProdList.add(standMap.get(prod)); }
if(! updateStdProdList.isEmpty()){
update updateStdProdList; }catch(Exception e){
                      system.debug(‘Exception is’+e); } } if(! custProdTodelete.isEmpty()){
                      delete custProdTodelete; }catch(Exception e){
                      system.debug(‘Exception in delete is’+e); } } } }

Execute Batch Apex: Open Developer console and open and click on debug and click on Open Execute Anonymous Window
❖Then paste the below code
Id batchJobId = Database.executeBatch(new BatchapexproductUpdate());
For testing, open any of the custom product and give the expiry date Custom as less than today and save.
❖ For example ‘Custom Product’ Prod_customer_Quantity__c is 3 and standard Product’s Prod_Standard_Quantity__c
Now open the execute anonymous window and click on execute
❖After executing the batch apex the custom product is deleted and custom product quantity (3) is added to the standard product quantity. Now standard Product quantity is 97+3=100