Sub topic 3
Anatomy of a batch class: start, execute, finish
This chapter assumes you can write Apex classes, run SOQL queries and DML statements, and know the basic governor limits. It walks through the three methods that every batch class must implement.
The Database.Batchable interface
A batch class implements Database.Batchable<SObject>. The type in angle brackets is the record type the job passes to each chunk. The interface requires three methods. Salesforce calls them in a fixed order.
| Method | Runs | Purpose |
|---|---|---|
| `start` | Once, at the beginning | Defines which records to process |
| `execute` | Once per chunk | Does the work on a list of records |
| `finish` | Once, at the end | Runs after all chunks complete |
A minimal example
This class sets a rating on every account that has none.
public class AccountRatingBatch implements Database.Batchable<SObject> {
public Database.QueryLocator start(Database.BatchableContext bc) {
return Database.getQueryLocator([
SELECT Id, Rating FROM Account WHERE Rating = null
]);
}
public void execute(Database.BatchableContext bc, List<Account> scope) {
for (Account a : scope) {
a.Rating = 'Cold';
}
update scope;
}
public void finish(Database.BatchableContext bc) {
System.debug('Job ' + bc.getJobId() + ' finished.');
}
}start
start returns a Database.QueryLocator built from a SOQL query. A query locator can cover up to 50 million records, which is why it suits large jobs. The query runs once. Salesforce then divides the result into chunks.
execute
execute receives a List of records, called the scope. Each call runs in its own transaction, so governor limits reset for every chunk. Declare the parameter as the concrete type, such as List<Account>, so you can use fields without casting. If one execute call throws an unhandled exception, only that chunk rolls back. Chunks that already finished stay committed, and the job continues with the next chunk.
finish
finish runs once after the last chunk, whether or not some chunks failed. Use it for summaries, notification emails, or starting a follow-up job. The BatchableContext argument gives you getJobId(), which is the Id of the AsyncApexJob record that tracks this run.
Common mistakes
- Querying inside
executefor the full data set. Thestartquery defines the records. Query inexecuteonly for related data, and do it once per chunk, not once per record. - Assuming instance variables persist between
executecalls. Each chunk runs in a separate transaction, and the class is re-created. WithoutDatabase.Stateful, values you set in one chunk are lost. - Doing DML inside the loop. Collect records in a list and run one DML statement per chunk, as the example does.
Exercise
A batch job processes 1,000 records with a chunk size of 200. How many times does Salesforce call start, execute, and finish, and what happens to the other chunks if the third execute call throws an unhandled exception?
Show answer
start is called once, execute five times, and finish once. If the third execute call fails, only that chunk's changes roll back. The first two chunks stay committed, the remaining chunks still run, and finish still runs at the end.