Sub topic 4
Queueable Apex: future methods with fewer restrictions
This chapter assumes you know basic Apex classes, SOQL and DML, and how a trigger runs inside one synchronous transaction. You should also have seen @future methods in the previous chapter.
Why Queueable exists
A @future method is easy to write, but it has hard limits. It must be static and void, and it accepts only primitives or collections of primitives. You get no job Id back, so you can't monitor it. You can't start one future method from another.
Queueable Apex removes those restrictions. You write a class that implements the Queueable interface, and you start it with System.enqueueJob. The job still runs asynchronously, in its own transaction, with the higher async governor limits.
| Feature | `@future` | Queueable |
|---|---|---|
| Parameter types | Primitives and collections of primitives | Any type, held in member variables |
| Returns a job Id | No | Yes |
| Can chain another async job | No | Yes, one child job |
| Needs a `static void` method | Yes | No, an instance `execute` method |
Writing a Queueable class
The class stores its input in member variables, set through the constructor. Because it is a normal object, those variables can hold sObjects, lists, maps, or your own classes.
public class AccountReviewJob implements Queueable {
private List<Account> accounts;
public AccountReviewJob(List<Account> accounts) {
this.accounts = accounts;
}
public void execute(QueueableContext ctx) {
for (Account a : accounts) {
a.Description = 'Reviewed';
}
update accounts;
}
}
// Enqueue it and keep the job Id for monitoring:
Id jobId = System.enqueueJob(new AccountReviewJob(accts));The execute method receives a QueueableContext. Call ctx.getJobId() inside the job to get its own Id. The jobId returned by System.enqueueJob is the same value, and you can look it up in the AsyncApexJob object.
How it runs
The call to System.enqueueJob only adds the job to a queue. Your current transaction finishes first. The platform runs execute later, in a new transaction, when a worker is free.
sequenceDiagramThe diagram below shows the order of events.
Two consequences follow from this order.
- The job does not run if the enqueuing transaction rolls back. The platform enqueues it as part of that transaction.
- The job sees data as it exists when it runs, not when you enqueued it. If a record changed in between, your member variable holds a stale copy. For important updates, re-query by Id inside
execute.
Limits to remember
- A single synchronous transaction can enqueue up to 50 jobs with
System.enqueueJob. An async transaction, such as a running Queueable job, can enqueue only one child. - Async transactions get higher limits than synchronous ones. For example, SOQL queries rise from 100 to 200, and heap rises from 6 MB to 12 MB.
- Member variables must be serializable. A variable you don't want serialized can be marked
transient. - For a callout, implement
Database.AllowsCalloutsalongsideQueueable.
public class PartnerCalloutJob implements Queueable, Database.AllowsCallouts {
public void execute(QueueableContext ctx) {
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Partner_API/ping');
req.setMethod('GET');
HttpResponse res = new Http().send(req);
System.debug(res.getStatusCode());
}
}This replaces the callout=true flag used by future methods.
Common mistakes
- Enqueuing inside a loop. Each call counts toward the 50-job limit. Collect records first, then enqueue one job with the whole list.
- Enqueuing two children from
execute. The second call throws aLimitException. Chain one job at a time. The next chapter covers chaining. - Passing a huge list. The job runs in one transaction, so a list of 100,000 records still hits DML and heap limits. Large volumes belong in Batch Apex.
Exercise
A trigger enqueues a Queueable job and then throws an exception that rolls back the transaction. Does the job run? Name one other difference from a future method that this Queueable has.
Show answer
No. The enqueue is part of the rolled-back transaction, so the job never runs. Any of these differences is correct: it can take non-primitive parameters such as sObject lists, it returns a job Id from System.enqueueJob, or it can chain a child job.