Sub topic 11
Monitoring and aborting jobs
This chapter assumes you can write a Database.Batchable class and start it with Database.executeBatch, and that you can write basic SOQL. After reading it, you will be able to check how far a job has progressed, find out why it failed, and stop a job that is running or waiting.
Where job information lives
Every batch job gets a row in the AsyncApexJob object when you queue it. Database.executeBatch returns that row's Id. Keep the Id if you will need to check the job later.
There are three ways to see the job:
- Setup, Apex Jobs. A list of recent jobs with status, progress, and an Abort link for active ones.
- Setup, Apex Flex Queue. Jobs waiting in the
Holdingstate, with the option to reorder them. - SOQL on
AsyncApexJob. Use this when you want to check progress from code, a script, or a report.
A batch job usually appears as a parent row with JobType = 'BatchApex'. Each execute call also gets a child row with JobType = 'BatchApexWorker'. Filter on BatchApex unless you want the child rows.
The fields that matter
| Field | Meaning |
|---|---|
| `Status` | Where the job is in its life cycle (see below). |
| `TotalJobItems` | Number of batches (chunks), not records. |
| `JobItemsProcessed` | Batches finished so far. |
| `NumberOfErrors` | Number of batches that failed with an unhandled exception. |
| `ExtendedStatus` | Text of the first error, when there is one. |
| `CreatedDate`, `CompletedDate` | When the job was queued and when it ended. |
| `ApexClass.Name` | The batch class that is running. |
Two points often cause confusion. First, the counters count batches. A job over 1,000,000 records with a batch size of 200 has 5,000 job items. Second, NumberOfErrors is not a count of failed records. If you use Database.update(records, false), records can fail without any batch failing, so NumberOfErrors stays at 0. Track record-level failures yourself with Database.Stateful, as covered in the chapter on partial failures.
TotalJobItems can be 0 while the job is Queued or Preparing, because the job has not run start yet. Guard against dividing by zero when you compute progress.
The status life cycle
| Status | What it means |
|---|---|
| `Holding` | Waiting in the Flex Queue for a free slot. |
| `Queued` | Accepted and waiting to start. |
| `Preparing` | The `start` method is running and the data set is being set up. |
| `Processing` | `execute` calls are running. |
| `Completed` | All batches were attempted and `finish` ran. |
| `Failed` | The job stopped because of a system or unrecoverable error. |
| `Aborted` | Someone or something stopped the job. |
A job can end as Completed even though some batches threw exceptions. In that case NumberOfErrors is greater than 0. Always check both fields.
Checking progress from code
Run this in Anonymous Apex to see the most recent runs of one batch class:
List<AsyncApexJob> jobs = [
SELECT Id, Status, JobItemsProcessed, TotalJobItems,
NumberOfErrors, ExtendedStatus, CreatedDate, CompletedDate
FROM AsyncApexJob
WHERE JobType = 'BatchApex'
AND ApexClass.Name = 'AccountRatingBatch'
ORDER BY CreatedDate DESC
LIMIT 10
];
for (AsyncApexJob j : jobs) {
Decimal pct = j.TotalJobItems == 0
? 0
: (100.0 * j.JobItemsProcessed / j.TotalJobItems).setScale(1);
System.debug(j.Id + ' ' + j.Status + ' ' + pct + '% batches done, '
+ j.NumberOfErrors + ' failed batches. ' + j.ExtendedStatus);
}To check one job you started yourself, filter by Id instead:
Id jobId = Database.executeBatch(new AccountRatingBatch(), 200);
AsyncApexJob job = [
SELECT Status, JobItemsProcessed, TotalJobItems, NumberOfErrors
FROM AsyncApexJob WHERE Id = :jobId
];
System.debug(job.Status);The status read here is a snapshot. A job queued a moment ago will most likely show Queued or Holding. Re-run the query later, or poll from a scheduled job or a tool outside Salesforce.
Reading the result inside finish
The finish method is the natural place to record the outcome, because it runs once at the end. It receives the same job Id through the context:
public void finish(Database.BatchableContext bc) {
AsyncApexJob job = [
SELECT Status, NumberOfErrors, JobItemsProcessed, TotalJobItems, ExtendedStatus
FROM AsyncApexJob WHERE Id = :bc.getJobId()
];
if (job.NumberOfErrors > 0) {
System.debug(LoggingLevel.ERROR,
job.NumberOfErrors + ' of ' + job.TotalJobItems
+ ' batches failed. First error: ' + job.ExtendedStatus);
// Send an email, create a log record, or publish a platform event here.
}
}Use this check to alert someone. A job that fails at 3 a.m. will not be noticed unless something raises the alarm.
The context also offers bc.getChildJobId(), which is the Id of the BatchApexWorker row for the current execute call. Writing it into your own log records helps you match a log line to a specific chunk.
Aborting a job
Call System.abortJob with the job Id:
System.abortJob(jobId);You can also use the Abort link on the Apex Jobs page. The call works on jobs in Holding, Queued, Preparing, and Processing. After the abort, the status becomes Aborted.
Keep these points in mind:
- Committed work stays. Each
executeis its own transaction. Batches that already finished are saved, and an abort does not undo them. After an abort, your data is partly processed. - A batch in flight. The abort takes effect between batches in the usual case. Do not assume a particular
executecall will be cut short. - Do not depend on
finish. After an abort, do not rely onfinishto clean up. Put any essential cleanup somewhere that does not depend on a normal ending. - Design for re-runs. Because an abort leaves partial results, the job should be safe to start again. The usual approach is a query that selects only unprocessed records, such as
WHERE Rating = nullin the example class. A second run then picks up where the first stopped.
To stop every active run of a batch class, for example during an incident:
List<AsyncApexJob> active = [
SELECT Id FROM AsyncApexJob
WHERE JobType = 'BatchApex'
AND ApexClass.Name = 'AccountRatingBatch'
AND Status IN ('Holding', 'Queued', 'Preparing', 'Processing')
];
for (AsyncApexJob j : active) {
System.abortJob(j.Id);
}
System.debug('Aborted ' + active.size() + ' job(s).');If the class chains another job from finish, aborting the first job may stop the chain from continuing. Check for follow-on jobs as well.
Scheduled jobs are separate
A schedule created with System.schedule is not an AsyncApexJob. It is a row in CronTrigger, and its Id is what System.schedule returns. Aborting a running batch does not cancel the schedule, so the next run will start another job at the scheduled time. To stop the schedule, abort the CronTrigger Id:
CronTrigger ct = [
SELECT Id, State, NextFireTime, CronJobDetail.Name
FROM CronTrigger
WHERE CronJobDetail.Name = 'Nightly account rating'
];
System.debug(ct.State + ', next run: ' + ct.NextFireTime);
System.abortJob(ct.Id);Common mistakes
- Treating
JobItemsProcessedas a record count. It counts batches. - Reading
Status = 'Completed'as success without checkingNumberOfErrors. - Aborting the batch while the schedule is still active, so a new job starts later.
- Expecting an abort to roll back completed batches.
- Writing a batch whose query cannot be re-run safely after a partial run.
Exercise
A batch job over 1,000,000 Accounts with a batch size of 200 shows Status = Completed, TotalJobItems = 5000, JobItemsProcessed = 5000, NumberOfErrors = 3. The class uses Database.update(scope, false). What do these numbers tell you about the failed records, and what else would you check?
Show answer
The 3 errors mean three whole batches threw unhandled exceptions, so up to 600 records were not processed (3 batches of up to 200). They do not count records that failed inside Database.update with allOrNone set to false, because those failures do not fail the batch. Read ExtendedStatus for the first exception message. Then check the record-level counters that the class keeps with Database.Stateful, or the SaveResult logs, to find the records that failed individually. Because the job can be re-run on records that are still unprocessed, you can fix the cause and run it again.