Examples

Apex Batch Job

Running a Batch Job

Apex batch job processes Opportunities with Database.Batchable.

Introduction to Apex Batch Jobs

Apex Batch Jobs are a key feature in Salesforce that allow developers to process large volumes of records asynchronously. They are particularly useful when dealing with operations that exceed normal processing limits.

In this guide, we'll focus on how to use an Apex Batch Job to process Opportunity records efficiently using the Database.Batchable interface.

Implementing Database.Batchable Interface

The Database.Batchable interface in Apex provides the structure for creating batch jobs. Implementing this interface requires defining three methods: start, execute, and finish.

Understanding the Batchable Methods

  • start: This method is invoked at the beginning of the batch job. It returns a QueryLocator or an iterable that contains the records to be processed. In our example, we're querying Opportunity records that are in the 'Prospecting' stage.
  • execute: This method is called for each batch of records. The list of records is passed as the scope parameter. In the example, we're updating the Description field of each Opportunity.
  • finish: This method is executed after all batches have been processed. It's typically used for post-processing operations, such as logging or sending notifications.

Executing the Batch Job

To run the batch job, you need to create an instance of the batch class and call the Database.executeBatch method.

In the above code, the 200 represents the batch size, which determines the number of records processed in each batch. Adjust this number based on your requirements and Salesforce governor limits.

Previous
Trigger