Sub topic 12
Monitoring and managing async jobs
This chapter assumes you can write Apex classes, run SOQL, and have already written a future method, a Queueable class, a Batch class, and a Schedulable class. It covers how to see what those jobs are doing after they leave your transaction, and how to stop or reorder them.
Why monitoring is a separate skill
An async job runs after your code has returned. If it fails, the user who triggered it sees nothing, and your original transaction has already committed. Salesforce keeps a record of each job so you can look it up later. Knowing where those records live, and what their statuses mean, is how you find failures before users report them.
There are three places to look:
- The Apex Jobs page in Setup shows most async work, including future, Queueable, and Batch jobs.
- The Scheduled Jobs page in Setup lists schedules created with
System.schedule. - SOQL on
AsyncApexJobandCronTriggergives the same data in code.
The AsyncApexJob object
Every future call, Queueable job, batch job, and scheduled execution creates an AsyncApexJob row. You can query it like any other sObject.
| Field | What it tells you |
|---|---|
| `JobType` | `Future`, `Queueable`, `BatchApex`, `BatchApexWorker`, `ScheduledApex`, and others |
| `Status` | `Holding`, `Queued`, `Preparing`, `Processing`, `Completed`, `Failed`, `Aborted` |
| `ApexClass.Name` | The class that is running |
| `MethodName` | The future method name, for future jobs |
| `JobItemsProcessed` | Batches finished so far (batch jobs) |
| `TotalJobItems` | Batches the job will run in total |
| `NumberOfErrors` | Count of batches that failed |
| `ExtendedStatus` | The first error message, when there is one |
| `ParentJobId` | The job that created this one, such as a chained Queueable |
| `CreatedDate`, `CompletedDate` | Timing |
This query lists the last day of failed or aborted work, newest first:
List<AsyncApexJob> problems = [
SELECT Id, JobType, Status, ApexClass.Name, MethodName,
NumberOfErrors, ExtendedStatus, CreatedDate, CompletedDate
FROM AsyncApexJob
WHERE Status IN ('Failed', 'Aborted')
AND CreatedDate = LAST_N_DAYS:1
ORDER BY CreatedDate DESC
LIMIT 50
];
for (AsyncApexJob j : problems) {
System.debug(j.JobType + ' ' + j.ApexClass.Name + ' ' + j.Status
+ ': ' + j.ExtendedStatus);
}Salesforce removes finished AsyncApexJob rows after about seven days. If you need a longer history, write your own log record, for example from a finalizer or from a batch finish method.
Job statuses and what they mean
A job moves through a small set of states. Batch jobs can also wait in the Apex Flex Queue before they start.
Two statuses cause most confusion:
Preparingappears only for batch jobs, whilestartruns and the query locator is built.Holdingmeans the batch job is in the Flex Queue, waiting for one of the five batch slots.
A job with status Completed can still have NumberOfErrors greater than zero. In a batch job, each execute call is its own transaction. A failed scope does not stop later scopes, so the job as a whole completes anyway. Always check NumberOfErrors, not just Status.
Following a batch job's progress
Database.executeBatch returns the job Id. Keep it and you can poll the job:
Id batchId = Database.executeBatch(new StaleLeadBatch(), 200);
AsyncApexJob job = [
SELECT Status, JobItemsProcessed, TotalJobItems, NumberOfErrors
FROM AsyncApexJob
WHERE Id = :batchId
];
System.debug(job.Status + ': ' + job.JobItemsProcessed + ' of '
+ job.TotalJobItems + ' batches, errors=' + job.NumberOfErrors);TotalJobItems is the number of execute calls, not the number of records. With 10,000 records and a scope of 200, expect 50.
Batch jobs also create BatchApexWorker rows. Filter on JobType = 'BatchApex' when you want one row per job rather than extra internal rows.
Monitoring Queueable jobs and chains
System.enqueueJob returns an Id, and that Id is the AsyncApexJob Id. A job that enqueues a child produces a new row whose ParentJobId points at the parent. That lets you rebuild a chain:
Id firstJobId = System.enqueueJob(new ChunkedUpdateJob(accountList));
List<AsyncApexJob> chain = [
SELECT Id, ParentJobId, Status, CreatedDate
FROM AsyncApexJob
WHERE JobType = 'Queueable'
AND (Id = :firstJobId OR ParentJobId = :firstJobId)
ORDER BY CreatedDate
];This query finds only the first child. A chain of unknown length needs repeated queries, or a log record written by each link. For failures, attach a finalizer. Its FinalizerContext includes getAsyncApexJobId(), so the log line can point back to the exact job row.
Monitoring scheduled jobs
A scheduled job has two kinds of records. The schedule itself is a CronTrigger. Each time it fires, an AsyncApexJob row with JobType = 'ScheduledApex' is created. System.schedule returns the CronTrigger Id.
List<CronTrigger> schedules = [
SELECT Id, CronJobDetail.Name, CronExpression, State,
PreviousFireTime, NextFireTime, TimesTriggered
FROM CronTrigger
WHERE CronJobDetail.JobType = '7'
ORDER BY NextFireTime
];
for (CronTrigger ct : schedules) {
System.debug(ct.CronJobDetail.Name + ' state=' + ct.State
+ ' next=' + ct.NextFireTime);
}CronJobDetail.JobType = '7' selects scheduled Apex. Other values are other kinds of scheduled work such as reports. A healthy schedule has State = 'WAITING' and a NextFireTime in the future. A schedule whose NextFireTime is null has finished and will not run again.
A scheduler class that only starts a batch will almost always show a successful ScheduledApex row, even when the batch it launched fails. To judge the real result, look at the BatchApex row that follows it.
Stopping and reordering jobs
System.abortJob stops a job, given an AsyncApexJob Id for a batch job or a CronTrigger Id for a schedule:
// Abort a running or waiting batch job
System.abortJob(batchId);
// Remove a schedule so it never fires again
System.abortJob(cronTriggerId);Aborting a batch job lets the current execute call finish. Work already committed stays committed. It is not rolled back. Scopes that have not started never run.
The Flex Queue holds batch jobs that are waiting because five batch jobs are already queued or running. It can hold up to 100. You can read and reorder it in Apex:
List<AsyncApexJob> waiting = [
SELECT Id, ApexClass.Name, CreatedDate
FROM AsyncApexJob
WHERE Status = 'Holding'
ORDER BY CreatedDate
];
if (!waiting.isEmpty()) {
// Make the last waiting job run next
FlexQueue.moveJobToFront(waiting[waiting.size() - 1].Id);
}The Apex Flex Queue page in Setup offers the same reordering with drag and drop.
Catching batch errors as they happen
Polling works, but you can also be told. If a batch class implements Database.RaisesPlatformEvents, a failed scope publishes a BatchApexErrorEvent. You subscribe to it with a trigger:
public class RiskyBatch implements Database.Batchable<SObject>, Database.RaisesPlatformEvents {
public Database.QueryLocator start(Database.BatchableContext bc) {
return Database.getQueryLocator('SELECT Id FROM Account');
}
public void execute(Database.BatchableContext bc, List<Account> scope) {
// work that might throw
}
public void finish(Database.BatchableContext bc) {}
}
trigger BatchErrorLogger on BatchApexErrorEvent (after insert) {
for (BatchApexErrorEvent e : Trigger.new) {
System.debug(LoggingLevel.ERROR, 'Batch ' + e.AsyncApexJobId
+ ' failed: ' + e.Message + ' | records: ' + e.JobScope);
}
}JobScope lists the record Ids of the failed scope. That tells you exactly which records to retry. Neither AsyncApexJob.ExtendedStatus nor an email gives you that. (The trigger is a separate file from the class.)
Watching the org-wide cap
All async executions share a daily allowance, roughly 250,000 or 200 times the number of user licenses, whichever is greater. Batch counts once per execute call. You can read the current usage in Apex:
System.OrgLimit lim = System.OrgLimits.getMap().get('DailyAsyncApexExecutions');
System.debug('Used ' + lim.getValue() + ' of ' + lim.getLimit());Run this from a scheduled job and raise an alert at 80 percent. Doing so catches a runaway chain or a small-scope batch over a very large table before the limit blocks all async work.
Which tool to inspect for which job
| Job type | Where to look | Useful handle |
|---|---|---|
| Future | `AsyncApexJob` where `JobType = 'Future'` | `MethodName`; no Id returned by the call |
| Queueable | `AsyncApexJob` where `JobType = 'Queueable'` | Id from `System.enqueueJob`, `ParentJobId` |
| Batch | `AsyncApexJob` where `JobType = 'BatchApex'` | Id from `Database.executeBatch`, `JobItemsProcessed` |
| Scheduled | `CronTrigger`, plus `AsyncApexJob` for each run | Id from `System.schedule`, `NextFireTime` |
Future methods are the hardest to track, because the call returns nothing. If you need to trace one, pass a correlation value as a parameter and write it to a log record inside the method.
Common mistakes
- Reading only
Status. ACompletedbatch can hide failed scopes. CheckNumberOfErrors. - Expecting history older than a week from
AsyncApexJob. - Treating a successful scheduler run as proof its batch worked.
- Aborting a
ScheduledApexrow. Abort theCronTriggerinstead, or the schedule keeps firing. - Polling a job inside a loop in one transaction. A SOQL query does not wait for the job, so you only burn query limits. Check from another job or from a UI instead.
Exercise
A nightly scheduler starts a batch job. The Scheduled Jobs page shows the schedule as WAITING with a recent PreviousFireTime, but users say stale leads were not cleaned up. Which records do you query next, and which fields do you read?
Show answer
Query AsyncApexJob where JobType = 'BatchApex' and ApexClass.Name is the batch class, ordered by CreatedDate descending. Read Status, NumberOfErrors, JobItemsProcessed, TotalJobItems, and ExtendedStatus. The schedule only proves the scheduler class ran. The batch row shows whether its execute calls failed. For record-level detail, add Database.RaisesPlatformEvents to the batch and read BatchApexErrorEvent.JobScope.
Exercise
You called Database.executeBatch six times in a row and the sixth job has status Holding. What does that mean, and how can you make it run before the fifth job in the queue?
Show answer
Five batch jobs are already queued or running, so the sixth waits in the Apex Flex Queue. If other jobs are also Holding, call FlexQueue.moveJobToFront(jobId) with the sixth job's Id, or reorder it on the Apex Flex Queue page in Setup. It will start when one of the five active slots frees up.