Sub topic 4
Enqueuing a job and tracking it with AsyncApexJob
This chapter assumes you can write a basic Queueable class (the previous chapter) and that you know governor limits and per-transaction limits. It covers what System.enqueueJob does, what the returned ID means, and how to read a job's progress from the AsyncApexJob object.
What happens when you enqueue
System.enqueueJob takes an instance of a class that implements Queueable. It places a request on the asynchronous queue and returns an Id right away. It does not run execute.
Id jobId = System.enqueueJob(new AccountRatingJob(accountIds));
System.debug('Queued job ' + jobId);The calling transaction keeps going and finishes normally. The platform starts the job later, in its own transaction, when resources are available. Three consequences follow:
- Any code after
enqueueJobruns before the job'sexecutemethod. The job never sees work the caller does after enqueuing, except through data that was already committed. - The job gets its own governor limits. Heavy work in
executedoes not count against the caller. - Your code cannot wait for the result. The only way to learn what happened is to look at the job record or at the data the job changed.
The object is serialized at the moment you enqueue. Changes you make to the instance afterward are not seen by the job. The next chapter on state covers this in more detail.
The AsyncApexJob object
Every asynchronous Apex run has a row in AsyncApexJob, which you query with SOQL like any other object. For queueable jobs, these fields matter most:
| Field | Meaning |
|---|---|
| `Id` | The value returned by `System.enqueueJob`. |
| `JobType` | `Queueable` for queueable jobs. Other values include `BatchApex`, `Future`, and `ScheduledApex`. |
| `Status` | Where the job is in its life cycle (see below). |
| `ApexClassId` | The ID of the Apex class that was enqueued. |
| `NumberOfErrors` | Count of errors. For a queueable that threw an unhandled exception, this is greater than zero. |
| `ExtendedStatus` | Text describing the failure, such as the exception message. |
| `CreatedDate` | When the job was enqueued. |
| `CompletedDate` | When the job finished. It is empty until then. |
| `ParentJobId` | For a job enqueued by another job, the ID of the job that enqueued it. |
| `CreatedById` | The user whose context enqueued the job. |
A queueable job moves through these values of Status:
The Status picklist also has Holding and Preparing. Those belong to Batch Apex and the flex queue. You will not normally see them on a queueable.
Reading a job's status
A small helper class keeps the query in one place. It selects the fields above for one job ID.
public class JobMonitor {
public static AsyncApexJob getJob(Id jobId) {
List<AsyncApexJob> jobs = [
SELECT Id, Status, JobType, NumberOfErrors, ExtendedStatus,
CreatedDate, CompletedDate, ParentJobId, ApexClass.Name
FROM AsyncApexJob
WHERE Id = :jobId
];
return jobs.isEmpty() ? null : jobs[0];
}
public static Boolean isFinished(Id jobId) {
AsyncApexJob job = getJob(jobId);
return job != null
&& (job.Status == 'Completed'
|| job.Status == 'Failed'
|| job.Status == 'Aborted');
}
}The query uses a list and not a direct assignment. If the row is missing, a direct assignment would throw a QueryException. A missing row is possible if you pass a stale or wrong ID.
Run it from Anonymous Apex after enqueuing:
Id jobId = System.enqueueJob(new AccountRatingJob(new List<Id>()));
AsyncApexJob job = JobMonitor.getJob(jobId);
System.debug(job.Status + ' / errors: ' + job.NumberOfErrors);The status you see here is usually Queued. Calling the helper again a few seconds later, in a separate execution, shows a later state. Do not loop inside one transaction waiting for the status to change. The job runs in another transaction, so the loop only burns your CPU limit.
Finding many jobs
To see everything that ran recently for one class, filter on ApexClass.Name and JobType:
List<AsyncApexJob> recent = [
SELECT Id, Status, NumberOfErrors, ExtendedStatus, CreatedDate, CompletedDate
FROM AsyncApexJob
WHERE JobType = 'Queueable'
AND ApexClass.Name = 'AccountRatingJob'
AND CreatedDate = LAST_N_DAYS:1
ORDER BY CreatedDate DESC
LIMIT 50
];To find failures only, add AND Status = 'Failed'. In the browser, the same data is under Setup > Apex Jobs, which lists job type, status, and the failure text.
Knowing your own job ID
Inside execute, the QueueableContext argument gives the ID of the running job:
public void execute(QueueableContext context) {
Id myJobId = context.getJobId();
System.debug('Running as job ' + myJobId);
}This is useful for logging and for tying job output to the AsyncApexJob row. In a chain, each job has its own ID. The child's ParentJobId points to the job that enqueued it, so you can walk a chain from the last job back to the first.
Aborting a job
System.abortJob takes a job ID and cancels the job if it has not started.
System.abortJob(jobId);The status becomes Aborted. A job that is already Processing runs to the end of its transaction. Aborting a finished job has no effect on the result you already have. The Apex Jobs page in Setup also lets an administrator abort a queued job.
Limits on enqueuing
Enqueuing is itself limited, and you can read the numbers at run time:
| Context | Maximum queueable jobs enqueued |
|---|---|
| Synchronous transaction (trigger, controller, Anonymous Apex) | 50 |
| Inside a queueable job's `execute` | 1 |
The check is made when you call enqueueJob. The 51st call in one synchronous transaction throws a System.LimitException, which you cannot catch. The whole transaction fails. Read the counters before you enqueue in a loop:
Integer used = Limits.getQueueableJobs();
Integer max = Limits.getLimitQueueableJobs();
System.debug(used + ' of ' + max + ' queueable jobs used');A second, org-wide limit exists: the number of asynchronous Apex executions in 24 hours. Queueable runs count toward it, along with batch and future runs. Many small jobs eat into that allowance faster than one job that does the same work in a loop. The full rules, including how limits apply to chains, are in the chapter on enqueue and chain limits.
Testing the enqueue and its result
Queueable jobs enqueued in a test do not run until Test.stopTest(). At that point the platform runs them synchronously, and the AsyncApexJob row reflects the outcome:
@IsTest
private class JobTrackingTest {
@IsTest
static void jobCompletes() {
Account a = new Account(Name = 'Test Account');
insert a;
Test.startTest();
Id jobId = System.enqueueJob(new AccountRatingJob(new List<Id>{ a.Id }));
Test.stopTest();
AsyncApexJob job = [
SELECT Status, NumberOfErrors
FROM AsyncApexJob
WHERE Id = :jobId
];
System.assertEquals('Completed', job.Status);
System.assertEquals(0, job.NumberOfErrors);
}
}Asserting on the data the job changed is usually the stronger check. Asserting on AsyncApexJob adds a check that the run did not end in Failed.
Common errors
- Treating the ID as proof of success.
enqueueJobreturning an ID only means the request was accepted. CheckStatuslater. - Querying immediately and expecting
Completed. In the same transaction, the job has not started. - Enqueuing in a loop. The limit of 50 is reached on bulk operations.
- Enqueuing twice from a queueable. Only one child job is allowed from
execute, so a second call fails. - Missing the failure text. When
StatusisFailed, readExtendedStatusfor the message.NumberOfErrorsalone tells you nothing about the cause.
Exercise
A trigger on Contact enqueues one queueable job for each Contact in Trigger.new. A data load inserts 200 Contacts in one batch. What happens, and how do you fix it? Then name the field you would query on AsyncApexJob to read the exception text of a job that failed.
Show answer
The 51st System.enqueueJob call in the synchronous transaction throws an uncatchable System.LimitException, and the whole transaction fails. Fix it by collecting the Contact IDs into one list and enqueuing a single job that receives the list in its constructor and processes all of them in execute. For a failed job, query ExtendedStatus (and check Status = 'Failed' and NumberOfErrors).