# How can developers utilize the AsyncApexJob object to monitor and audit asynchronous job execution?

**Topic:** Apex · **Difficulty:** Medium · **Tags:** Apex, Asynchronous Apex, Monitoring

Read it on the site: https://www.forcechallenges.com/interview-questions/how-can-developers-utilize-the-asyncapexjob-object-to-monitor-and-audit-asynchronous-job-execution

## Answer

**Basics:** When you call `Database.executeBatch`, `System.enqueueJob`, or a future method is invoked, Salesforce creates an `AsyncApexJob` row you can read. Setup has matching UIs: Apex Jobs, Apex Flex Queue and Scheduled Jobs. Developers use SOQL to check whether a job finished, how many records were processed and whether errors occurred.

**How it works:** `Database.executeBatch` and `System.enqueueJob` return the job Id; query `AsyncApexJob` by that Id. Useful fields: `Status` (Holding, Queued, Preparing, Processing, Completed, Failed, Aborted), `JobType` (BatchApex, BatchApexWorker, Future, Queueable, ScheduledApex, and others), `JobItemsProcessed`, `TotalJobItems`, `NumberOfErrors`, `ExtendedStatus`, `ApexClassId`, `MethodName`, `CreatedDate`, `CompletedDate`, `ParentJobId`. Scheduled job definitions live in `CronTrigger` and `CronJobDetail`; `System.schedule` returns a CronTrigger Id.

**Advanced / deep dive:** For auditing, build a small monitor: a scheduled job or LWC that polls open jobs, alerts on `Failed` or `NumberOfErrors > 0`, and checks capacity before submitting a new batch (only 5 batch jobs active concurrently; overflow goes to the Flex Queue, up to 100 Holding jobs, reorderable with `FlexQueue.moveJobToFront`). Batch jobs also create `BatchApexWorker` children, so filter by `JobType`. Use `System.abortJob(jobId)` to cancel. `AsyncApexJob` shows technical status only: it knows a chunk failed but not which record or why, so combine it with a custom log object, `BatchApexErrorEvent` (with `Database.RaisesPlatformEvents`), and Finalizers. History is kept for a limited time after completion (commonly cited as about 7 days; verify in current documentation), so archive what you need for compliance into a custom object.

**Code / config example:**
```apex
Id jobId = Database.executeBatch(new OppAmountBatch(), 200);

AsyncApexJob j = [
    SELECT Id, Status, JobItemsProcessed, TotalJobItems, NumberOfErrors, ExtendedStatus
    FROM AsyncApexJob WHERE Id = :jobId
];
System.debug(j.Status + ' ' + j.JobItemsProcessed + '/' + j.TotalJobItems);

// Is anything of my class still active?
Integer active = [SELECT COUNT() FROM AsyncApexJob
                  WHERE ApexClass.Name = 'OppAmountBatch'
                    AND Status IN ('Holding','Queued','Preparing','Processing')];
```

**Hidden gotchas & must-remember points:**
- `Status = 'Completed'` with `NumberOfErrors > 0` means some chunks failed; completed does not mean successful.
- `JobItemsProcessed` and `TotalJobItems` are batch-chunk counts, not record counts.
- Unhandled-exception details are in `ExtendedStatus` and the email to the code author, not per record.
- Scheduled jobs are tracked through CronTrigger, not just AsyncApexJob.
- Records are purged after a retention window.
- Tests cannot see real async rows unless you use `Test.stopTest()` to run them.

**Best practice:** Log your own job outcomes in a custom object and use `AsyncApexJob` for live status and capacity checks.

---
Source: ForceChallenges · last updated 2026-11-02
