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 (per-transaction caps on queries, DML rows, heap and CPU time). It covers the three methods of Database.Batchable, the order in which they run, and the mistakes that most often break a first batch class.
The contract: Database.Batchable
A batch class implements Database.Batchable<SObject>. The type in angle brackets is the type of record the job processes. The interface requires three methods:
| Method | Runs | Transaction | Purpose |
|---|---|---|---|
| `start` | Once, at the beginning | Its own | Defines the full set of records to process |
| `execute` | Once per chunk of records | One per chunk | Does the real work on a chunk |
| `finish` | Once, at the end | Its own | Runs follow-up work such as notifications or chaining |
Each method receives a Database.BatchableContext. Call bc.getJobId() on it to get the Id of the AsyncApexJob record that tracks the job.
Here is a minimal batch class that gives a rating to accounts that have 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.');
}
}How a job flows through the three methods
The platform calls start once. It then splits the returned records into chunks and calls execute for each chunk. After the last chunk it calls finish.
The diagram shows the chunks side by side, but they do not run in parallel. Chunks of one job run one after another. Each execute call is its own transaction, so a failure in chunk 2 does not undo chunk 1. If an unhandled exception ends chunk 2, the platform rolls back only that chunk's changes and moves on to chunk 3. The job continues, and the failed chunk is counted in NumberOfErrors on the AsyncApexJob record.
start: defining the record set
start runs once and returns either a Database.QueryLocator or an Iterable. The next chapter compares the two in detail. For now, remember what each gives you.
- A
QueryLocatorwraps a SOQL query. The platform streams its results, and the query can return up to 50 million records. This is the usual choice. - An
Iterablelets you supply records from your own logic. The total number of rows is then subject to the normal per-transaction query row limit.
A common mistake is to run the query yourself and return a list. A List<SObject> is an Iterable, so the code compiles, but the list is built in one transaction and is limited to 50,000 query rows. That defeats the purpose of using a batch.
Keep start light. Do not do the heavy processing there. It runs in its own transaction with its own limits, and it only needs to describe the work.
execute: the work, one chunk at a time
execute receives the context and a List of records. The default chunk size is 200 records. Because each call is a separate transaction, the governor limits reset for every chunk. A job over five million accounts never has to fit five million records into one transaction's heap or DML limit. It only has to fit 200 records.
Three points matter inside execute.
- Write it in bulk. Treat
scopeas a list. Do not query or run DML inside theforloop. A chunk of 200 records with one SOQL query per record exceeds the 100-query limit. - The parameter type must match. If
startreturns a query overAccount, you can declare the second parameter asList<Account>. If it isList<SObject>, you must cast. Declaring a type that does not match the query fails at runtime. - Instance variables do not persist by default. The platform may create a fresh instance of your class for each
executecall. A counter you increment in one chunk will usually be back to its starting value in the next. Chapter "Sharing state across batches with Database.Stateful" covers the fix.
finish: after all chunks
finish runs once after the last execute, whether or not some chunks failed. Typical uses are:
- Reading the
AsyncApexJobrecord to report the outcome. - Sending an email or creating a log record.
- Starting a follow-up job.
This example reads the job record in finish.
public void finish(Database.BatchableContext bc) {
AsyncApexJob job = [
SELECT Id, Status, NumberOfErrors, JobItemsProcessed, TotalJobItems
FROM AsyncApexJob WHERE Id = :bc.getJobId()
];
System.debug('Status: ' + job.Status + ', errors: ' + job.NumberOfErrors);
}NumberOfErrors counts failed chunks, not failed records. A chunk of 200 records that throws an unhandled exception counts as one error, even though all 200 changes were rolled back.
Starting the job
Creating an instance of the class does nothing by itself. Pass it to Database.executeBatch. The method returns the Id of the AsyncApexJob.
Id jobId = Database.executeBatch(new AccountRatingBatch(), 200);
System.debug('Started batch job ' + jobId);The second argument is the chunk size. If you leave it out, the platform uses 200. The job is queued and starts when resources are free, so the call returns before any start or execute code has run. Do not expect the data to be changed on the line after executeBatch.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `Too many query rows: 50001` in `start` | Returned a `List` built from a SOQL query instead of a `QueryLocator` | Use `Database.getQueryLocator` |
| `Too many SOQL queries: 101` in `execute` | Query inside the loop over `scope` | Query once before the loop, using a `Set` of Ids |
| Counter is always small at the end | Instance field reset between chunks | Implement `Database.Stateful` |
| Whole chunk missing changes | One bad record threw an unhandled exception and rolled back the chunk | Use `Database.update(scope, false)` and check results |
| Class does not compile | A required method has the wrong signature | Match the interface exactly, including `Database.BatchableContext` |
Quick check
Exercise
A batch job processes 1,000 accounts with a chunk size of 200. During the third chunk, an unhandled exception is thrown from execute. How many chunks are committed, how many times is execute called, and does finish run?
Show answer
Five chunks are processed, so execute is called five times. The first two chunks are committed. The third chunk is rolled back and counted as one error in NumberOfErrors. The fourth and fifth chunks still run and commit, and finish runs once at the end. So four chunks are committed and one is rolled back.
Exercise
Why is it a mistake to write start as return [SELECT Id FROM Account]; with a return type of Iterable<SObject> when the table holds millions of rows?
Show answer
The list returned by the inline query is built in a single transaction, so it is subject to the 50,000 query row limit and the job fails in start. Returning Database.getQueryLocator(...) lets the platform stream up to 50 million records without loading them all at once.