Sub topic 6
Starting a Job with Database.executeBatch
This chapter assumes you can write Apex classes, run SOQL and DML, and know the basic governor limits. It also assumes you have a class that implements Database.Batchable<SObject>, such as the AccountRatingBatch from the previous chapter.
What executeBatch does
Database.executeBatch does not run your batch immediately. It adds the job to the asynchronous queue and returns the Id of an AsyncApexJob record. Salesforce starts the job when resources are free. Then it calls start once, calls execute once per chunk, and calls finish once at the end.
Id jobId = Database.executeBatch(new AccountRatingBatch(), 200);
System.debug('Started batch job ' + jobId);The method takes two arguments:
- The batch instance. Its constructor runs now, in the calling transaction. Any values you pass in must be serializable if the class is
Database.Stateful. - The scope size (optional). This is the number of records passed to each
executecall. If you leave it out, the default is 200. The allowed range is 1 to 2,000 for aQueryLocator.
The job lifecycle
Each execute call runs in its own transaction with fresh governor limits. The caller's transaction has already ended by then.
Where you can call it
You can call executeBatch from anonymous Apex, a trigger, a controller, a Schedulable class, a Queueable, or the finish method of another batch. Some rules apply:
- A single transaction can add at most 100 jobs to the queue with
executeBatch. - Up to 5 batch jobs can be queued or active at once. Extra jobs go into the Flex Queue, which a later chapter covers.
- Be careful in triggers. A trigger that starts a batch on every save can flood the queue.
Using the returned Id
The Id points to an AsyncApexJob record. You can query it to see progress:
AsyncApexJob job = [
SELECT Status, JobItemsProcessed, TotalJobItems, NumberOfErrors
FROM AsyncApexJob
WHERE Id = :jobId
];
System.debug(job.Status + ': ' + job.JobItemsProcessed + ' of ' + job.TotalJobItems);Status moves through Holding, Queued, Preparing, Processing, and then Completed, Failed, or Aborted. A later chapter covers monitoring and aborting in detail.
Passing parameters
Add a constructor to your batch class and store the values in fields. This keeps the job reusable:
public class RatingBatch implements Database.Batchable<SObject> {
private final String targetRating;
public RatingBatch(String targetRating) {
this.targetRating = targetRating;
}
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 = targetRating;
}
update scope;
}
public void finish(Database.BatchableContext bc) {}
}Database.executeBatch(new RatingBatch('Warm'), 200);Common errors
- Expecting results right after the call. The job has only been queued, so queries on the changed data will show old values.
- Calling
executeBatchfrom a batchexecutemethod. This throws aSystem.AsyncException. Start follow-up jobs fromfinishinstead. - Running the
executelogic by calling it directly. This skips the per-chunk transactions and applies the limits of one transaction. - Setting the scope too high for heavy logic. A chunk that hits a limit fails as a whole. A later chapter covers tuning.
Exercise
You call Database.executeBatch(new RatingBatch('Warm'), 50) in anonymous Apex and, on the next line, query for accounts with Rating = 'Warm'. Why might the query return nothing, and what does the call return?
Show answer
The call only queues the job and returns the Id of an AsyncApexJob record. The start and execute methods run later in separate transactions, so no accounts have been updated yet when the query runs. You can query AsyncApexJob with the returned Id to check progress.