Batch Apex is a Salesforce-specific feature that processes large amounts of data or records in smaller, more manageable pieces. This functionality is essential for working within Salesforce’s governor limits, which ensure optimal job performance in a multi-tenant environment. To prevent processes from exceeding these limits, developers use Batch Apex, which divides the workload into smaller chunks, allowing the execution of queries, DML operations, and more without surpassing Salesforce’s set thresholds.

Key Features of Batch Apex

  • Handles Large Data Sets: Batch Apex allows for the processing of thousands or even millions of records, handling up to 200 records per batch.
  • Optimizes Resource Utilization: By breaking the workload into smaller transactions, it helps respect Salesforce’s governor limits, making it ideal for bulk data processing operations.
  • Asynchronous Execution: Unlike other Apex code, Batch Apex runs asynchronously, meaning it doesn’t interfere with real-time user processes. It can be queued or scheduled based on system resource availability.

Three Core Methods

  • start(): Prepares the records to be processed, typically by querying or loading data.
  • execute(): Processes each batch of records that is returned by the start() method.
  • finish(): Executes post-processing actions after all batches are completed, such as sending notifications or logging.

Use Cases

  • Bulk updating or deleting records.
  • Performing complex data calculations across large data sets.
  • Bulk data processing, especially when integrating with external systems.
  • Sending mass email alerts based on defined criteria.

Organizations that handle large data volumes or require automation of tasks involving the processing of many records rely on Batch Apex to stay within Salesforce’s governor limits while efficiently completing their tasks.

Batch Apex Example

Here I am providing simple example to understand how to run batch apex programatically. Below is the simple apex class which implements Database.Batchable interface.

global class batchAccountUpdate implements Database.Batchable<sObject> {
	
	global Database.QueryLocator start(Database.BatchableContext BC) {
		String query = 'SELECT Id,Name FROM Account';		
		return Database.getQueryLocator(query);
	}
	
	global void execute(Database.BatchableContext BC, List<Account> scope) {
		for(Account a : scope) {
			a.Name = a.Name + '******';
		}
		update scope;
	}
	
	global void finish(Database.BatchableContext BC) {
	}
}

Now, I want to run this batch apex class. To run the apex job, you have to call “database.executeBatch” method. open developer console and execute below line of code.

batchAccountUpdate bc = new batchAccountUpdate();
database.executeBatch(bc);

After executing the above code, the related job will run. To see/monitor Batch apex jobs go to Setup->jobs->Apex Jobs. Here you will see the status of Batch apex jobs like submitted date, Job Type, Status, Total Batches, Bathes processed, failures, submitted by, Completion date, Apex Class & Apex Job ID. And also you can abort the jobs which are in processing.

Batch Apex Example: Updating Salesforce Account Records

The above example demonstrates how to use Batch Apex to update a batch of Salesforce Account records by appending some characters (******) to the account names. Below is a breakdown of the code and relevant terminology:

1. Batch Apex Class Declaration


global class batchAccountUpdate implements Database.Batchable<sObject> {

global: This keyword makes the class accessible throughout the Salesforce instance, which is necessary for Batch Apex classes.

Database.Batchable: This interface allows the class to process records in batches. You must implement three methods: start(), execute(), and finish(). The <sObject> signifies that the batchable class will operate on Salesforce objects, such as standard or custom objects.

2. start() Method


global Database.QueryLocator start(Database.BatchableContext BC) {
    String query = 'SELECT Id, Name FROM Account';
    return Database.getQueryLocator(query);
}

start(): This method prepares the records to be processed in batches by executing a SOQL query to fetch records from Salesforce.

Database.QueryLocator: Used to retrieve large sets of records and pass them into the batch for processing.

getQueryLocator(query): Returns a QueryLocator object to iterate over individual records. In this case, the query retrieves the Id and Name fields from all Account records.

3. execute() Method

global void execute(Database.BatchableContext BC, List<Account> scope) {
    for(Account a : scope) {
        a.Name = a.Name + '******';
    }
    update scope;
}

execute(): This method processes the records returned by start() in batches, also known as scopes. Each scope contains a subset of records to be processed.

List<Account> scope: This list represents the batch of records to be updated.

The loop iterates through each Account record in the scope and appends '******' to the account’s name. After processing, the update DML operation commits the changes to the Salesforce database.

4. finish() Method


global void finish(Database.BatchableContext BC) {
    // Post-batch actions, if any
}

finish(): This method runs after all batches have been processed. Typically, this is where you would handle post-batch tasks such as logging or sending notifications. In this example, it is left empty.

Key Concepts in Batch Apex

  • BatchableContext: This object tracks the state of the batch job throughout the process.
  • Scope: A subset of records processed in a single batch.
  • Governor Limits: Salesforce enforces limits on operations to ensure resources are shared fairly. Batch Apex helps work around these limits by processing records in manageable chunks.

Summary

This Batch Apex class is designed to append '******' to the names of many Account records in Salesforce. It handles large datasets by breaking them into smaller, manageable batches, preventing governor limit issues. The process involves querying records in the start() method, updating them in execute(), and optionally performing additional tasks in finish(). Batch Apex is ideal for automating bulk data processing.

If you want to run apex job after, click on the button on the Visualforce page, then create a page and implement above login in controller & call that method after clicking on button in a Visualforce page.