Salesforce Development: Understanding Apex Batch
Learn how to create a basic Salesforce Apex Batch
Hi everyone ๐, this article highlights Salesforce Development especially working on the Apex programming language. In some cases, you have business requirements to process a large amount of data like for instance they want you to update more than 50,000 records ๐คฏ. Basic Apex class can't handle this large volume of data to process because of the Salesforce governor limits.
Don't be sad my friend, Apex Batch to the rescue ๐ฅณ. Using Batch Apex, you can process records asynchronously in batches or chunks to stay within platform limits. Without further ado let's start coding.
Start blogging with Hashnode
Resources
github.com/pelayochristian/apex-development
Apex Batch Structure
In your class, implement the Database.Batchable Interface as well the following methods:
- start()
- execute()
- finish()
// Implements Database.Batchable Interface
public class BGBasicAccountBatch implements Database.Batchable<SObject> {
public (Database.QueryLocator | Iterable<SObject>) start(Database.BatchableContext context) {
/** Retrieve records */
}
public void execute(Database.BatchableContext context, List<Account> scope) {
/** Processing records in batches */
}
public void finish(Database.BatchableContext context) {
/** Final method where you can also do a post-processing operations */
}
}
Apex Batch Sample
/**
* Basic implementation of Apex Batch. For this demo we process Account
* Records.
* Batchable Class Implements the following method:
* - start()
* - execute()
* - finish()
*
* @author Christian Pelayo (pelayochristian.dev@gmail.com)
*/
public class BGBasicAccountBatch implements Database.Batchable<SObject> {
/**
* Entry method of our Batch Class
* @param context batch context
* @return `Iterable<Account>`
*/
public Database.QueryLocator start(Database.BatchableContext context) {
return Database.getQueryLocator('SELECT Id, Name FROM Account');
}
/**
* Main execution of our Batch Class. In our demo this we've just
* updating account name by adding ' - updated'.
* @param context batch context
* @param scope list if Accounts
*/
public void execute(Database.BatchableContext context, List<Account> scope) {
List<Account> accountToUpdate = new List<Account>();
try {
for (Account account : scope) {
account.Name = account.Name + ' - updated';
accountToUpdate.add(account);
}
update accountToUpdate;
} catch (Exception e) {
System.debug('Exception message: ' + e.getMessage());
}
}
/**
* Finished method of our Batch Class. For our demo, we added some
* monitoring by sending an email to the user after the batch
* execution finished.
* @param context batch context
*/
public void finish(Database.BatchableContext context) {
AsyncApexJob a = [
SELECT Id, Status, NumberOfErrors, JobItemsProcessed, TotalJobItems, CreatedBy.Email
FROM AsyncApexJob
WHERE Id = :context.getJobId()
];
//Send an email to the user who executed the Batch Job
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
String[] toAddress = new String[]{
a.CreatedBy.Email
};
mail.setToAddresses(toAddress);
mail.setSubject('Apex job Status' + a.Status);
mail.setPlainTextBody('The apex job processed ' + a.TotalJobItems +
' Batches with ' + a.NumberOfErrors + ' failures');
Messaging.sendEmail(new Messaging.SingleEmailMessage[]{
mail
});
}
}
Run Apex Batch Manually
In your Salesforce Org, open your Developer Console and run this in the Anonymous Apex Window. After executing it will create an instance of Apex Job.
Database.executeBatch(new BGBasicAccountBatch());
Monitoring your Apex Jobs
Go to Setup > Apex Jobs
Result
Based on the Apex Batch above, " - updated" should concatenate on the Account Name field.
Conclusion
Awesome! ! ! you already know how to create a basic Apex Batch. Hope it helps. ๐ Thank you! Happy hacking ... ๐ป