Apex - Batch Processing (2024)

Apex - Batch Processing (1)

  • Apex Programming Tutorial
  • Apex - Home
  • Apex - Overview
  • Apex - Environment
  • Apex - Example
  • Apex - Data Types
  • Apex - Variables
  • Apex - Strings
  • Apex - Arrays
  • Apex - Constants
  • Apex - Decision Making
  • Apex - Loops
  • Apex - Collections
  • Apex - Classes
  • Apex - Methods
  • Apex - Objects
  • Apex - Interfaces
  • Apex - DML
  • Apex - Database Methods
  • Apex - SOSL
  • Apex - SOQL
  • Apex - Security
  • Apex - Invoking
  • Apex - Triggers
  • Apex - Trigger Design Patterns
  • Apex - Governer Limits
  • Apex - Batch Processing
  • Apex - Debugging
  • Apex - Testing
  • Apex - Deployment
  • Apex Useful Resources
  • Apex - Quick Guide
  • Apex - Resources
  • Apex - Discussion
  • Selected Reading
  • UPSC IAS Exams Notes
  • Developer's Best Practices
  • Questions and Answers
  • Effective Resume Writing
  • HR Interview Questions
  • Computer Glossary
  • Who is Who

'; var adpushup = adpushup || {}; adpushup.que = adpushup.que || []; adpushup.que.push(function() { adpushup.triggerAd(ad_id); });

In this chapter, we will understand Batch Processing in Apex. Consider a scenario wherein, we will process large number of records on daily basis, probably the cleaning of data or maybe deleting some unused data.

What is Batch Apex?

Batch Apex is asynchronous execution of Apex code, specially designed for processing the large number of records and has greater flexibility in governor limits than the synchronous code.

When to use Batch Apex?

Using Batch Apex

When we are using the Batch Apex, we must implement the Salesforce-provided interface Database.Batchable, and then invoke the class programmatically.

You can monitor the class by following these steps −

To monitor or stop the execution of the batch Apex Batch job, go to Setup → Monitoring → Apex Jobs or Jobs → Apex Jobs.

Apex - Batch Processing (2)

Apex - Batch Processing (3)

Database.Batchable interface has the following three methods that need to be implemented −

  • Start
  • Execute
  • Finish

Let us now understand each method in detail.

Start

The Start method is one of the three methods of the Database.Batchable interface.

Syntax

global void execute(Database.BatchableContext BC, list<sobject<) {}

This method will be called at the starting of the Batch Job and collects the data on which the Batch job will be operating.

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.

  • Use the iterable object when you have complex criteria to process the records. Database.QueryLocator determines the scope of records which should be processed.

Execute

Let us now understand the Execute method of the Database.Batchable interface.

Syntax

global void execute(Database.BatchableContext BC, list<sobject<) {}

where, list<sObject< 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

We will now discuss the Finish method of the Database.Batchable interface.

Syntax

global void finish(Database.BatchableContext BC) {}

This method gets called at the end and you can do some finishing activities like sending an email with information about the batch job records processed and status.

Batch Apex Example

Let us consider an example of our existing Chemical Company and assume that we have requirement to update the Customer Status and Customer Description field of Customer Records which have been marked as Active and which have created Date as today. This should be done on daily basis and an email should be sent to a User about the status of the Batch Processing. Update the Customer Status as 'Processed' and Customer Description as 'Updated Via Batch Job'.

// Batch Job for Processing the Recordsglobal class CustomerProessingBatch implements Database.Batchable<sobject> { global String [] email = new String[] {'test@test.com'}; // Add here your email address here // Start Method global Database.Querylocator start (Database.BatchableContext BC) { return Database.getQueryLocator('Select id, Name, APEX_Customer_Status__c, APEX_Customer_Decscription__c From APEX_Customer__c WHERE createdDate = today AND APEX_Active__c = true'); // Query which will be determine the scope of Records fetching the same } // Execute method global void execute (Database.BatchableContext BC, List<sobject> scope) { List<apex_customer__c> customerList = new List<apex_customer__c>(); List<apex_customer__c> updtaedCustomerList = new List<apex_customer__c>(); // List to hold updated customer for (sObject objScope: scope) { APEX_Customer__c newObjScope = (APEX_Customer__c)objScope ; // type casting from generic sOject to APEX_Customer__c newObjScope.APEX_Customer_Decscription__c = 'Updated Via Batch Job'; newObjScope.APEX_Customer_Status__c = 'Processed'; updtaedCustomerList.add(newObjScope); // Add records to the List System.debug('Value of UpdatedCustomerList '+updtaedCustomerList); } if (updtaedCustomerList != null && updtaedCustomerList.size()>0) { // Check if List is empty or not Database.update(updtaedCustomerList); System.debug('List Size ' + updtaedCustomerList.size()); // Update the Records } } // Finish Method global void finish(Database.BatchableContext BC) { Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage(); // 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()); // below code will send an email to User about the status mail.setToAddresses(email); mail.setReplyTo('test@test.com'); // Add here your email address mail.setSenderDisplayName('Apex Batch Processing Module'); mail.setSubject('Batch Processing '+a.Status); mail.setPlainTextBody('The Batch Apex job processed' + a.TotalJobItems+'batches with '+a.NumberOfErrors+'failures'+'Job Item processed are'+a.JobItemsProcessed); Messaging.sendEmail(new Messaging.Singleemailmessage [] {mail}); }}

To execute this code, first save it and then paste the following code in Execute anonymous. This will create the object of class and Database.execute method will execute the Batch job. Once the job is completed then an email will be sent to the specified email address. Make sure that you have a customer record which has Active as checked.

// Paste in Developer ConsoleCustomerProessingBatch objClass = new CustomerProessingBatch();Database.executeBatch (objClass);

Once this class is executed, then check the email address you have provided where you will receive the email with information. Also, you can check the status of the batch job via the Monitoring page and steps as provided above.

If you check the debug logs, then you can find the List size which indicates how many records have been processed.

Limitations

We can only have 5 batch job processing at a time. This is one of the limitations of Batch Apex.

Scheduling the Apex Batch Job using Apex Detail Page

You can schedule the Apex class via Apex detail page as given below −

Step 1 − Go to Setup ⇒ Apex Classes, Click on Apex Classes.

Apex - Batch Processing (4)

Step 2 − Click on the Schedule Apex button.

Apex - Batch Processing (5)

Step 3 − Provide details.

Apex - Batch Processing (6)

Scheduling the Apex Batch Job using Schedulable Interface

You can schedule the Apex Batch Job using Schedulable Interface as given below −

// Batch Job for Processing the Recordsglobal class CustomerProessingBatch implements Database.Batchable<sobject> { global String [] email = new String[] {'test@test.com'}; // Add here your email address here // Start Method global Database.Querylocator start (Database.BatchableContext BC) { return Database.getQueryLocator('Select id, Name, APEX_Customer_Status__c, APEX_Customer_Decscription__c From APEX_Customer__c WHERE createdDate = today AND APEX_Active__c = true'); // Query which will be determine the scope of Records fetching the same } // Execute method global void execute (Database.BatchableContext BC, List<sobject> scope) { List<apex_customer__c> customerList = new List<apex_customer__c>(); List<apex_customer__c> updtaedCustomerList = new List<apex_customer__c>();//List to hold updated customer for (sObject objScope: scope) { APEX_Customer__c newObjScope = (APEX_Customer__c)objScope ;//type casting from generic sOject to APEX_Customer__c newObjScope.APEX_Customer_Decscription__c = 'Updated Via Batch Job'; newObjScope.APEX_Customer_Status__c = 'Processed'; updtaedCustomerList.add(newObjScope);//Add records to the List System.debug('Value of UpdatedCustomerList '+updtaedCustomerList); } if (updtaedCustomerList != null && updtaedCustomerList.size()>0) { // Check if List is empty or not Database.update(updtaedCustomerList); System.debug('List Size' + updtaedCustomerList.size()); // Update the Records } } // Finish Method global void finish(Database.BatchableContext BC) { Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage(); // 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()); // below code will send an email to User about the status mail.setToAddresses(email); mail.setReplyTo('test@test.com');//Add here your email address mail.setSenderDisplayName('Apex Batch Processing Module'); mail.setSubject('Batch Processing '+a.Status); mail.setPlainTextBody('The Batch Apex job processed' + a.TotalJobItems+'batches with '+a.NumberOfErrors+'failures'+'Job Item processed are'+a.JobItemsProcessed); Messaging.sendEmail(new Messaging.Singleemailmessage [] {mail}); } // Scheduler Method to scedule the class global void execute(SchedulableContext sc) { CustomerProessingBatch conInstance = new CustomerProessingBatch(); database.executebatch(conInstance,100); }}// Paste in Developer ConsoleCustomerProessingBatch objClass = new CustomerProcessingBatch();Database.executeBatch (objClass);

Advertisem*nts

';adpushup.triggerAd(ad_id); });

Apex - Batch Processing (2024)
Top Articles
Latest Posts
Article information

Author: Jamar Nader

Last Updated:

Views: 5841

Rating: 4.4 / 5 (55 voted)

Reviews: 94% of readers found this page helpful

Author information

Name: Jamar Nader

Birthday: 1995-02-28

Address: Apt. 536 6162 Reichel Greens, Port Zackaryside, CT 22682-9804

Phone: +9958384818317

Job: IT Representative

Hobby: Scrapbooking, Hiking, Hunting, Kite flying, Blacksmithing, Video gaming, Foraging

Introduction: My name is Jamar Nader, I am a fine, shiny, colorful, bright, nice, perfect, curious person who loves writing and wants to share my knowledge and understanding with you.