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{
}
Batchable interface have 3 main pre-defined methods which you must need to implement and those methods are
- start
- execute
- 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) 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:
- A reference to the Database.BatchableContext object.
- 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 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
- getJobId – Returns the ID of the batch Job.
- 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{
public Database.QueryLocator start(Database.BatchableContext BC){
return Database.getQueryLocator('SELECT Id, Name FROM Account');
}
public void execute(Database.BatchableContext BC, List 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{
public Database.QueryLocator start(Database.BatchableContext BC){
return Database.getQueryLocator('SELECT Id, Name FROM Account');
}
public void execute(Database.BatchableContext BC, List 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{
public Database.QueryLocator start(Database.BatchableContext BC){
return Database.getQueryLocator('SELECT Id, Name FROM Account');
}
public void execute(Database.BatchableContext BC, List 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.
[…] the previous blog post, we talked about what is Batch Apex in Salesforce and we also have discussed about that we can schedule the batch apex to run at a […]