Introduction to Batch Apex in Salesforce

Batch Apex is a way to process a large number of records asynchronously in Salesforce. It divides the job into smaller batches, each of which can be processed separately.

This helps in reducing the load on the system and ensures that the process runs efficiently without hitting governor limits.

In this article we'll show you some batch class examples in Salesforce

Batch Apex in Salesforce

Creating Batch Apex

Batch Apex is implemented by creating a class that implements the Database.Batchable interface. The Salesforce batch class interface includes three methods: start, execute, and finish.

Define the Batch Class

Create a new Apex class that implements the Database.Batchable interface. Here is the batch apex syntax in Salesforce:

public class MyBatchClass implements Database.Batchable<SObject> {
    public Database.QueryLocator start(Database.BatchableContext context) {
        // Return query locator for records to process
    }

    public void execute(Database.BatchableContext context, List<SObject> scope) {
        // Process each batch of records
    }

    public void finish(Database.BatchableContext context) {
        // Perform any finalization tasks
    }
}

Implement the start Method:

In the start method, you need to return a query locator that defines the set of records to be processed in the batch. For example, if you want to process all Accounts, the start method could look like this:

public Database.QueryLocator start(Database.BatchableContext context) {
    return Database.getQueryLocator([SELECT Id, Name FROM Account]);
}

Implement the execute Method:

The execute method is where you define the logic to process each batch of records. For example, let's say you want to update the Account records:
public void execute(Database.BatchableContext context, List<SObject> scope) {
    List<Account> accountsToUpdate = new List<Account>();
    for (SObject record : scope) {
        Account acc = (Account)record;
        // Perform your logic on the Account record
        acc.Name = 'Updated Name';
        accountsToUpdate.add(acc);
    }
    update accountsToUpdate;
}

Implement the finish Method:

The finish method is called after all batches are processed. It's used for any finalization tasks, such as sending notifications or logging.

public void finish(Database.BatchableContext context) {
    // Perform any cleanup, send emails or finalization tasks
}

Example - Updating Account Records with Batch Apex:

Let's put it all together in an example. Suppose you want to update the Name of all Account records with a certain condition. Here's how the batch class in Salesforce could look:

public class UpdateAccountBatch implements Database.Batchable<SObject> {
    public Database.QueryLocator start(Database.BatchableContext context) {
        return Database.getQueryLocator([SELECT Id, Name FROM Account WHERE Type = 'Prospect']);
    }

    public void execute(Database.BatchableContext context, List<SObject> scope) {
        List<Account> accountsToUpdate = new List<Account>();
        for (SObject record : scope) {
            Account acc = (Account)record;
            acc.Name = 'Updated Prospect';
            accountsToUpdate.add(acc);
        }
        update accountsToUpdate;
    }

    public void finish(Database.BatchableContext context) {
        // Perform any cleanup, send emails or finalization tasks
    }
}

Note: Keep in mind that this is a simplified example. In a real-world scenario, you might need to handle error handling, bulk processing considerations, and more complex logic.

Executing a Batch Apex

Here's the basic syntax to execute a batch in Salesforce:

MyBatchClass batch = new MyBatchClass(); // Replace with your batch class name
Database.executeBatch(batch);

Passing and Using Parameters

You can pass parameters to a batch job by using the Database.BatchableContext interface. This allows you to provide dynamic values to your batch job when it starts its execution. The Database.BatchableContext interface has a method called start() that you can use to pass parameters. Here's how you can do it:

Add a constructor to your apex batch class class that takes parameters and assigns them to instance variables. In this batch apex class in Salesforce example we will show you how you can create a dynamic query using parameters:

public class MyBatchClass implements Database.Batchable<SObject> {
    private String parameter1;
    private Integer parameter2;

    public MyBatchClass(String param1, Integer param2) {
        parameter1 = param1;
        parameter2 = param2;
    }

    public Database.QueryLocator start(Database.BatchableContext context) {
        // Use parameter1 and parameter2 in your query or logic

        String dynamicQuery = 'SELECT Id, Name FROM Account';
        dynamicQuery += ' WHERE Industry = \''+ parameter1 + '\' AND CALENDAR_YEAR(CreatedDate) =' + parameter2;
        
        return Database.getQueryLocator(dynamicQuery);
    }

    // Rest of the batch methods...
}

Execute the Batch with Parameters

When executing the batch, you can pass the parameters to the constructor of your batch class.

String paramValue1 = 'Finance';
Integer paramValue2 = 2023;

MyBatchClass batch = new MyBatchClass(paramValue1, paramValue2);
Database.executeBatch(batch);

Using parameters in a batch job allows you to make the batch process dynamic and adaptable to different scenarios. You can pass in values like record IDs, date ranges, user information, and more.

Governor Limits

Governor limits in Salesforce are designed to ensure the efficient use of resources and maintain the overall performance and stability of the platform.

Batch Apex also has its own set of governor limits that you need to consider when designing and executing batch jobs.

Batch Apex limits in Salesforce

Advantages of Batch Apex

Disadvantages of Batch Apex

Latest Articles: