Sub topic 6
Starting a Job with Database.executeBatch
This chapter covers how a batch job starts, what Database.executeBatch returns, and what happens between the call and the first execute invocation. It assumes you can write Apex classes, run SOQL and DML, and know the basic governor limits. You should also have a batch class with start, execute and finish, as in the previous chapter.
What executeBatch does
A class that implements Database.Batchable does nothing until you pass an instance to Database.executeBatch. The call does not run your batch logic. It places a request in the asynchronous job queue and returns right away.
Id jobId = Database.executeBatch(new AccountRatingBatch(), 200);
System.debug('Started batch job ' + jobId);The method returns the Id of an AsyncApexJob record. This Id identifies the job for monitoring, aborting and logging. Salesforce calls start, then execute once per chunk, then finish, later and on its own schedule, in separate transactions.
The method has two forms:
| Form | Meaning |
|---|---|
| `Database.executeBatch(batchable)` | Uses the default batch size of 200. |
| `Database.executeBatch(batchable, scopeSize)` | Sets how many records each `execute` call receives. |
Passing the size explicitly makes your intent visible to the next reader, even when you want the default.
The life of a job
After you call executeBatch, the job moves through several states. The Status field of the AsyncApexJob record shows them.
- Holding: the job waits in the Flex Queue because no processing slot is free. A later chapter covers this queue.
- Queued: the job waits for system resources.
- Preparing: the platform is running
startand building the list of records. - Processing:
executecalls are running. - Completed, Failed or Aborted: the job has ended.
Between submission and the first execute, the delay can range from seconds to much longer on a busy org. Do not write code that expects the job to have started when executeBatch returns.
Where you can call it
You can start a batch job from several places:
- Anonymous Apex in the Developer Console, which suits one-off runs.
- A trigger or controller. Use this with care, because every record save can start a job.
- A
Schedulableclass, covered in a later chapter. - The
finishmethod of another batch job, which is how chaining works. - A
Queueablejob.
Several limits apply to these callers:
- An org can have up to 5 batch jobs in the Queued or Active state at once. Further submissions go to the Flex Queue, which holds up to 100 jobs in Holding status.
- A single transaction can call
Database.executeBatchup to 100 times in total, because each call adds a job to the Flex Queue, but if the queue is full the call fails. - Calling
executeBatchfrom a trigger is risky, because bulk loads fire triggers in groups. A data load of 10,000 records fires the trigger 50 times, which can flood the queue. - From within
executeof a batch job, you cannot start another batch job. Chain fromfinishinstead.
Passing parameters to a job
The batch class instance is serialized when the job is queued. So you pass configuration through the constructor and store it in member variables. Here is a version of the rating job that accepts a rating value and a record limit.
public class ConfigurableRatingBatch implements Database.Batchable<SObject> {
private final String newRating;
private final Integer maxRecords;
public ConfigurableRatingBatch(String newRating, Integer maxRecords) {
this.newRating = newRating;
this.maxRecords = maxRecords;
}
public Database.QueryLocator start(Database.BatchableContext bc) {
return Database.getQueryLocator([
SELECT Id, Rating
FROM Account
WHERE Rating = null
LIMIT :maxRecords
]);
}
public void execute(Database.BatchableContext bc, List<Account> scope) {
for (Account a : scope) {
a.Rating = newRating;
}
update scope;
}
public void finish(Database.BatchableContext bc) {
System.debug('Job ' + bc.getJobId() + ' finished.');
}
}Start it like this:
Id jobId = Database.executeBatch(new ConfigurableRatingBatch('Warm', 10000), 200);The member variables must hold values that can be serialized. Avoid storing a non-serializable object, such as a Database.QueryLocator or an open HttpRequest, in a field. Mark such a field transient, and rebuild it inside execute.
Without Database.Stateful, the instance is created fresh for each execute call from the serialized state. Constructor values survive, but changes you make to fields inside execute do not carry to the next chunk. Stateful behavior has its own chapter.
Checking the job after you start it
Use the returned Id to query the job record.
Id jobId = Database.executeBatch(new AccountRatingBatch(), 200);
AsyncApexJob job = [
SELECT Id, Status, JobItemsProcessed, TotalJobItems, NumberOfErrors
FROM AsyncApexJob
WHERE Id = :jobId
];
System.debug('Status: ' + job.Status);
System.debug(job.JobItemsProcessed + ' of ' + job.TotalJobItems + ' chunks done');Run immediately after executeBatch, this query usually shows Queued or Holding. TotalJobItems stays 0 until start completes, so it is not a reliable total at this point. JobItemsProcessed counts chunks, not records.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `System.LimitException: Too many queueable jobs` or a flex queue error when starting | The Flex Queue holds 100 jobs and is full. | Start fewer jobs, or wait for the queue to drain. |
| Job sits in Holding | All 5 active slots are in use. | Wait, or reorder the job in the Flex Queue. |
| `System.AsyncException: Database.executeBatch cannot be called from a batch start, batch execute, or future method` | `executeBatch` was called inside `execute`, `start` or a `@future` method. | Move the call to `finish`, or use `Queueable`. |
| Constructor value is lost in `execute` | The field is not serializable, or the code changed it in an earlier `execute` without `Database.Stateful`. | Keep configuration fields read-only after construction. |
| Job starts but processes nothing | The `start` query returns no rows. | Test the query in the Developer Console first. |
| Batch size error | A size outside the allowed range of 1 to 2,000. | Pick a value within the range. |
Batch size at the call site
The second argument controls how many records go into each execute call. For a QueryLocator, the allowed range is 1 to 2,000. For an Iterable, the same limit applies to the size you pass. If you pass a value above 2,000 with a QueryLocator, Salesforce reduces it to 2,000.
A smaller size means more transactions and a longer total run. A larger size means more records share one set of governor limits. If your execute method does complex work per record, choose a number that keeps you under the CPU and SOQL limits, and lower it if you see limit exceptions. The next chapter discusses how to choose it.
A reusable launcher
When several places need to start the same job, wrap the call in one method. This gives you one place to add guards, such as a check for a job that is already running.
public class RatingBatchLauncher {
private static final Integer BATCH_SIZE = 200;
public static Id startIfIdle() {
List<AsyncApexJob> running = [
SELECT Id
FROM AsyncApexJob
WHERE ApexClass.Name = 'AccountRatingBatch'
AND JobType = 'BatchApex'
AND Status IN ('Holding', 'Queued', 'Preparing', 'Processing')
LIMIT 1
];
if (!running.isEmpty()) {
return running[0].Id;
}
return Database.executeBatch(new AccountRatingBatch(), BATCH_SIZE);
}
}The method returns the Id of the existing job when one is active, and otherwise starts a new one. It stops duplicates from being queued by repeated clicks or repeated trigger firings.
Summary of behavior
Database.executeBatchqueues the job and returns anAsyncApexJobId without running any batch code.- The optional second argument sets the records per
executecall, with a default of 200. - Pass configuration through the constructor, and keep it serializable.
- Guard against duplicate jobs when the call can be triggered repeatedly.
- Never call
executeBatchfrom insideexecute. Usefinishfor chaining.
Exercise
You call Database.executeBatch(new AccountRatingBatch(), 200) in anonymous Apex and immediately query the returned job Id. The Status is Queued and TotalJobItems is 0. Does this mean the job found no records? Explain what to check next.
Show answer
No. TotalJobItems stays 0 until start has run and the platform has counted the chunks, so a freshly queued job always shows 0. The job has not started yet. Wait and query the job again until Status is Processing or Completed. If it then still shows 0 total items, run the start query on its own in the Developer Console to see whether it returns any rows.
Exercise
A trigger on Account calls Database.executeBatch each time it runs, and a 10,000-row data load makes the Flex Queue fill up. Describe two ways to prevent this.
Show answer
First, add a guard that queries AsyncApexJob for a job of the same class in Holding, Queued, Preparing or Processing status, and skip the call when one exists, as in the launcher class above. Second, remove the call from the trigger and run the batch from a Schedulable class on a timer, so one job picks up all the changed records. Setting a flag on the changed records and letting the scheduled batch select them is a common pattern.