Sub topic 12
Monitoring and managing async jobs
This chapter assumes you can write basic Apex, run SOQL, and have already seen future, Queueable, Batch, and Scheduled Apex. Here you will learn where to see what your async jobs are doing and how to stop them.
Why monitoring matters
Async work runs after your code returns, so no user sees an error on screen. If a job fails, nobody is told unless you look. Salesforce records every async job, and you can inspect those records in two places: the Apex Jobs page in Setup and the AsyncApexJob object.
The Apex Jobs page
In Setup, search for Apex Jobs. The page lists recent jobs with their status, type, submitted date, and the number of batches processed. Use it for a quick look. Use AsyncApexJob when you need to check status from code or filter many jobs.
Querying AsyncApexJob
AsyncApexJob has one row per job. These fields matter most:
| Field | Meaning |
|---|---|
| `Id` | The job Id, which `System.enqueueJob` and `Database.executeBatch` return |
| `JobType` | `Future`, `Queueable`, `BatchApex`, `BatchApexWorker`, `ScheduledApex`, and others |
| `Status` | `Queued`, `Preparing`, `Processing`, `Holding`, `Completed`, `Failed`, or `Aborted` |
| `NumberOfErrors` | How many batches failed |
| `JobItemsProcessed` | Batches finished so far |
| `TotalJobItems` | Total batches for the job |
| `ExtendedStatus` | Error text when a job fails |
The query below checks the Queueable job from the earlier example by its Id:
Id jobId = System.enqueueJob(new AccountReviewJob(accts));
AsyncApexJob job = [
SELECT Id, Status, NumberOfErrors, JobItemsProcessed, TotalJobItems, ExtendedStatus
FROM AsyncApexJob
WHERE Id = :jobId
];
System.debug(job.Status + ' / errors: ' + job.NumberOfErrors);For a batch job, compare JobItemsProcessed to TotalJobItems to see progress.
List<AsyncApexJob> running = [
SELECT Id, ApexClass.Name, Status, JobItemsProcessed, TotalJobItems
FROM AsyncApexJob
WHERE JobType = 'BatchApex' AND Status IN ('Queued', 'Preparing', 'Processing')
];Checking the flex queue
Batch jobs beyond the limit of five active or queued jobs go into the Apex Flex Queue with the status Holding, up to 100 jobs. You can open the flex queue from the Apex Flex Queue page in Setup and reorder held jobs there. Held jobs start only when a slot opens.
Monitoring scheduled jobs
A scheduled job appears in two places. The Scheduled Jobs page in Setup shows the next run time and the owner. The CronTrigger object holds the same data for queries:
List<CronTrigger> schedules = [
SELECT Id, CronJobDetail.Name, State, NextFireTime, PreviousFireTime
FROM CronTrigger
WHERE CronJobDetail.Name = 'Nightly stale lead cleanup'
];Each time a schedule fires, it starts its own job. If the scheduler launches a batch, the batch gets a separate AsyncApexJob row. Check both when you debug.
Stopping and removing jobs
You can stop a job from the UI or from code.
- Abort a running or queued job. Call
System.abortJob(jobId). This works on batch, queueable, and scheduled job Ids. A scheduled job's Id is itsCronTriggerId. - Remove a schedule. Calling
System.abortJobwith theCronTriggerId deletes the schedule so it no longer fires.
for (CronTrigger ct : [
SELECT Id FROM CronTrigger
WHERE CronJobDetail.Name = 'Nightly stale lead cleanup'
]) {
System.abortJob(ct.Id);
}Monitoring from inside the job
Querying from outside shows status but not detail. For detail, add logging in the job:
- Use
System.debugwith debug logs enabled for the running user. This is fine for development. - Use a finalizer on Queueable jobs to record failures.
- Use
finishin a batch class to read theAsyncApexJobrow and reportNumberOfErrors.
public void finish(Database.BatchableContext bc) {
AsyncApexJob job = [
SELECT Status, NumberOfErrors, JobItemsProcessed, TotalJobItems
FROM AsyncApexJob
WHERE Id = :bc.getJobId()
];
System.debug('Batch ' + job.Status + ', failed batches: ' + job.NumberOfErrors);
}Job lifecycle
Exercise
A nightly scheduled class starts a batch job, and users report that the batch did not run last night. Which two records would you check first, and what would each tell you?
Show answer
Check the CronTrigger row for the schedule, which shows PreviousFireTime, NextFireTime, and State, so you know whether the schedule fired. Then check AsyncApexJob for a BatchApex row created at that time. Its Status, NumberOfErrors, and ExtendedStatus show whether the batch started and whether it failed.
Exercise
You call System.abortJob on a batch job that has processed 30 of 50 batches. What happens to the records changed by those 30 batches?
Show answer
Those changes stay committed, because each execute call ran as its own transaction. Only the unprocessed batches are stopped.