Understand Batch Processing in Salesforce Apex

Last updated on Nov 24 2021
Abha Kulkarni

Table of Contents

Understand Batch Processing in Salesforce Apex

In this blog, we’ll understand execution in Apex. Consider a scenario wherein, we’ll process sizable number of records on day to day, probably the cleaning of knowledge or even deleting some unused data.

What is Batch Apex?

Batch Apex is asynchronous execution of Apex code, specially designed for processing the massive number of records and has greater flexibility in governor limits than the synchronous code.
When to use Batch Apex?
• When you would like to process sizable number of records on day to day or maybe on specific time of interval then you’ll choose Batch Apex.
• Also, once you want an operation to be asynchronous then you’ll implement the Batch Apex. Batch Apex is exposed as an interface that has got to be implemented by the developer. Batch jobs are often programmatically invoked at runtime using Apex. Batch Apex operates over small batches of records, covering your entire record set and breaking the processing right down to manageable chunks of data.
Using Batch Apex
When we are using the Batch Apex, we must implement the Salesforce-provided interface Database. Batchable, then invoke the category programmatically.
You can monitor the category by following these steps −
To monitor or stop the execution of the batch Apex Batch job, attend Setup → Monitoring → Apex Jobs or Jobs → Apex Jobs.

salesforce 67
salesforce
salesforce 68
salesforce

Database.Batchable interface has the subsequent three methods that require to be implemented −
• Start
• Execute
• Finish
Let us now understand each method intimately .
Start
The Start method is one among the three methods of the Database.Batchable interface.
Syntax

global void execute(Database.BatchableContext BC, list

This method are going to be called at the starting of the Batch Job and collects the info on which the Batch job are going to be operating.
Consider the subsequent points to know the tactic −
• Use the Database.QueryLocator object once you are employing a simple query to get the scope of objects utilized in the batch job. during this case, the SOQL data row limit are going to be bypassed.
• Use the iterable object once 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
where, list0) {

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 top and you’ll do some finishing activities like sending an email with information about the batch job records processed and standing .

Batch Apex Example

Let us consider an example of our existing Chemical Company and assume that we’ve requirement to update the Customer Status and Customer Description field of Customer Records which are marked as Active and which have created Date as today. this could be done on day to day and an email should be sent to a User about the status of the execution . Update the Customer Status as ‘Processed’ and Customer Description as ‘Updated Via Batch Job’.

// Batch Job for Processing the Records
global class CustomerProessingBatch implements Database.Batchable {
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 can be determine the scope of Records fetching an equivalent 
}

// Execute method
global void execute (Database.BatchableContext BC, List scope) {
List customerList = new List();
List updtaedCustomerList = new List();

// List to carry 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 work 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 work 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 execution 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 reserve it then paste the subsequent code in Execute anonymous. this may create the thing of sophistication and Database.execute method will execute the Batch job. Once the work is completed then an email are going to be sent to the required email address. confirm that you simply have a customer record which has Active as checked.
// Paste in Developer Console
CustomerProessingBatch objClass = new CustomerProessingBatch();
Database.executeBatch (objClass);

Once this class is executed, then check the e-mail address you’ve got provided where you’ll receive the e-mail with information. Also, you’ll check the status of the batch job via the Monitoring page and steps as provided above.
If you check the debug logs, then you’ll find the List size which indicates what percentage records are processed.
Limitations
We can only have 5 batch job processing at a time. this is often one among the restrictions 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 − attend Setup ⇒ Apex Classes, Click on Apex Classes.

salesforce 69
salesforce

Step 2 − Click on the Schedule Apex button.

salesforce 70
salesforce

Step 3 − Provide details.

salesforce 71
salesforce

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 Records
global class CustomerProessingBatch implements Database.Batchable {
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 can be determine the scope of Records fetching an equivalent 
}

// Execute method
global void execute (Database.BatchableContext BC, List scope) {
List customerList = new List();
List updtaedCustomerList = new
List();//List to carry 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 work 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 work 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 execution 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 category 
global void execute(SchedulableContext sc) {
CustomerProessingBatch conInstance = new CustomerProessingBatch();
database.executebatch(conInstance,100);
}
}

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

So, this brings us to the end of blog. This Tecklearn ‘Understand Batch Processing in Salesforce Apex’ blog helps you with commonly asked questions if you are looking out for a job in Salesforce. If you wish to learn Salesforce and build a career in Salesforce domain, then check out our interactive, Salesforce Certification Training: Admin 201 and App Builder, that comes with 24*7 support to guide you throughout your learning period. Please find the link for course details:

Salesforce Certification Training: Admin 201 and App Builder

Salesforce Certification Training: Admin 201 and App Builder

About the Course

Salesforce Certification Training course will help you pass the Salesforce Administrator Exam (Admin 201) and the Salesforce App Builder (Dev 401) Exam. Concepts on Force.com Platform, AppExchange, SFDC Security Model, Service Cloud, Sales Cloud, Lightning App Builder, Salesforce Reports & Dashboard can be mastered in this Salesforce Training course. You can also configure the platform, manage users, find better ways to use the platform’s features, build applications with Salesforce Lightning, and more. Further, in this Salesforce certification training course, you will master App builder, Apex, Visualforce, etc.

Why Should you take Salesforce Admin 201 and App Builder Training?

• As per Indeed.com data, 200% global jump in Salesforce jobs since Jan 2016. Salesforce Certified Administrators earn an annual average salary of $87,000 but can go as high as $160,000 depending on their knowledge, skills, and experience.
• More than 200,000 companies worldwide use Salesforce platform. Salesforce leads the CRM market with 19.5 percent of market share – Forbes.
• The global CRM software market will reach US$40.26 billion in 2023, up from US$36.9 billion (2020) – Statista.

What you will Learn in this Course?

Salesforce Fundamentals
• Introduction to CRM concepts and Cloud computing
• Salesforce.com Overview and Fundamentals
• Understanding Salesforce Platform
Understanding Salesforce Platform
• Understanding Salesforce Terminologies and Introducing the force.com platform
• Understanding Salesforce Metadata and API
• Describe the capabilities of the core CRM objects in the Salesforce schema
• Identify common scenarios for extending an org using the AppExchange
• About Salesforce Certification
Introduction to Sales Cloud
• Sales Cloud
• Sales Process
• Sales Productivity Features
• Lead Management
• Lead auto response
• Lead assignment
• Web to lead
• Accounts and Contacts Management
• Opportunities
• Campaign Management
Security Model, User Management and Its Features
• Security Model Mind Map
• System Level or Org Level Security
• User Administration and Troubleshooting
• Permission Sets
• Profile Management
• User Actions
• Assigning Permission
• Session settings
• Activations
• Page layout assignment
• Tab setting
• Field level security
Object, Record and Field Level Features
• Custom Object
• Custom Field
• Data Types
• Relationship among Objects
• Working with App and Tabs
Data Handling and Processing
• Data Import and Export with Salesforce
• Insert, Update and Delete Data with Salesforce
• Export Data with UI
• Export Data using Data Loader Tool
Deployment
• SandBox
• Moving Data from SB to Production – Deployment
• Types of SandBox
• Change Sets
• Types of Change Sets
Application Cycle
• Milestones
• Sandboxes
• Change Sets
• Packages
Reports and Dashboards
Declarative Implementation in Salesforce
Salesforce Development and Apex Programming
• Apex Programming
• Apex Classes
• Apex Settings
• SOQL – Salesforce Object Query Language
• DML Commands
• Apex Class in Detail
• Apex Triggers
• Apex Testing
• Access Specifier in Salesforce
• Testing
Lightning in Salesforce
• Lightning Components
• Lightning Component Capabilities
• Lightning Components vs. Visualforce
Visual Force in Salesforce
• Standard Visualforce controller and controller extensions,
• Visualforce Page
• Understanding the MVC Pattern
• Tools for Visualforce Development
• Visual Force Components
WorkFlows in Salesforce
• Work Flows in Salesforce
• Types of Work Flows
• Work Flows Rules
About Preparation of Salesforce 201 and App Builder Certification exams

Got a question for us? Please mention it in the comments section and we will get back to you.

0 responses on "Understand Batch Processing in Salesforce Apex"

Leave a Message

Your email address will not be published. Required fields are marked *