Sub topic 4
Queueable Apex: future methods with fewer restrictions
This chapter assumes you can write basic Apex classes, run SOQL and DML, and read a governor limit error. It also assumes you know how a trigger runs inside one synchronous transaction, and that you have written a basic unit test. The previous chapter covered @future methods. Here you will see why Queueable Apex replaces them in most new code.
What Queueable Apex is
Queueable Apex is a class that implements the Queueable interface. You create an instance, pass it to System.enqueueJob, and Salesforce runs its execute method later in a separate transaction. Like a future method, it runs in the background with the higher asynchronous limits. Unlike a future method, it is an object, so it can carry state and be tracked.
| Capability | `@future` method | Queueable class |
|---|---|---|
| Parameters | Primitives and collections of primitives only | Any serializable member variables, including sObjects and custom types |
| Returns a job Id | No | Yes, from `System.enqueueJob` |
| Can chain a follow-up job | No | Yes, one child job per execution |
| Can be enqueued from a future method or batch | No (future cannot call future) | Yes |
| Callouts | `@future(callout=true)` | Implement `Database.AllowsCallouts` |
| Finalizer support | No | Yes |
| Enqueue limit per synchronous transaction | 50 calls | 50 jobs |
A first Queueable job
The class below stores a list of accounts in a member variable. The constructor receives the data, and execute uses it later.
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));Three things are worth noting.
- The constructor is your parameter list. With a future method you pass a
Set<Id>and re-query inside. With Queueable you can pass the records themselves. - The
QueueableContextargument gives youctx.getJobId(), the same Id thatSystem.enqueueJobreturned to the caller. - The
executemethod runs in its own transaction. If it throws an unhandled exception, its DML rolls back. The caller's transaction is unaffected, because it committed or failed independently.
How state is stored
When you call System.enqueueJob, the platform serializes the member variables of your instance. When the job starts, it deserializes them and calls execute. This has two practical consequences.
- The data is a snapshot taken at enqueue time. If another user changes an
Accountafter you enqueue, your list still holds the old field values. If your job updates those stale records, it can overwrite newer changes. For records that change often, pass Ids and re-query insideexecute. - Member variables must be serializable. A variable holding something that cannot be serialized, such as a
Database.QueryLocatoror an object that holds aHttpinstance, causes a runtime error at enqueue time. Mark such variablestransientand recreate them insideexecute.
public class SafeRefreshJob implements Queueable {
private Set<Id> accountIds;
private transient Http client;
public SafeRefreshJob(Set<Id> accountIds) {
this.accountIds = accountIds;
}
public void execute(QueueableContext ctx) {
client = new Http();
List<Account> fresh = [SELECT Id, Name FROM Account WHERE Id IN :accountIds];
for (Account a : fresh) {
a.Description = 'Refreshed';
}
update fresh;
}
}Callouts from a Queueable job
A future method needs callout=true on its annotation. A Queueable class opts in by also implementing the marker interface Database.AllowsCallouts. The interface has no methods.
public class PartnerSyncJob implements Queueable, Database.AllowsCallouts {
private Set<Id> accountIds;
public PartnerSyncJob(Set<Id> accountIds) {
this.accountIds = accountIds;
}
public void execute(QueueableContext ctx) {
List<Account> accts = [SELECT Id, Name FROM Account WHERE Id IN :accountIds];
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Partner_API/accounts');
req.setMethod('POST');
req.setBody(JSON.serialize(accts));
HttpResponse res = new Http().send(req);
if (res.getStatusCode() != 200) {
throw new CalloutException('Partner API returned ' + res.getStatusCode());
}
}
}If you forget Database.AllowsCallouts, the class compiles, and the first send call fails at runtime with an "uncommitted work pending" or callout-not-allowed style error. In a test, that failure shows up only if the test actually reaches the callout, so use Test.setMock to cover it.
Enqueueing from a trigger
The usual pattern is to collect Ids across the whole trigger batch and enqueue one job. Do not enqueue once per record.
public class OpportunityTriggerHandler {
public static void afterInsert(List<Opportunity> newRecords) {
Set<Id> accountIds = new Set<Id>();
for (Opportunity o : newRecords) {
if (o.AccountId != null) {
accountIds.add(o.AccountId);
}
}
if (!accountIds.isEmpty()) {
System.enqueueJob(new PartnerSyncJob(accountIds));
}
}
}A trigger can receive up to 200 records per chunk, and a bulk load can run many chunks in one transaction. If you enqueued per record, you would hit the limit of 50 jobs in one synchronous transaction after 50 records. One job per trigger invocation is safer, and a single job can handle the whole set.
Limits that apply
Queueable jobs run with asynchronous governor limits. These are larger than the synchronous ones: for example, 12 MB of heap, 60,000 ms of CPU time, and 200 SOQL queries per job. Each job also has its own limits. Nothing is shared with the transaction that enqueued it.
The limits specific to enqueueing are:
- A synchronous transaction can enqueue up to 50 jobs.
- A running Queueable job, future method, or batch
executemethod can enqueue only 1 job. - You can add a delay before the job starts with
System.enqueueJob(job, delayInMinutes), where the delay is 0 to 10 minutes. It is useful when you are waiting on an external system.
Common errors
- "Too many queueable jobs added to the queue: 51." You called
System.enqueueJobin a loop. Collect the work and enqueue once, or restructure the work into one job that chains itself. - Enqueueing a second job from a job. A running job can enqueue one child. A second
enqueueJobcall in the sameexecutethrows aLimitException. The next chapter covers chaining. - Stale data overwrites. The job saved a snapshot of records and updated them later. Pass Ids and re-query when freshness matters.
- Non-serializable state. A member variable that cannot be serialized fails at enqueue time. Use
transientand rebuild the value inexecute. - Callouts failing. The class does not implement
Database.AllowsCallouts. - Recursion. A job that updates records can fire a trigger that enqueues the same job again. Guard with a static flag or check
System.isQueueable()in the trigger handler.
Looking up the job
The Id returned by System.enqueueJob identifies a row in AsyncApexJob. You can query it to see whether the job is queued, running, or finished.
Id jobId = System.enqueueJob(new AccountReviewJob(accts));
AsyncApexJob job = [
SELECT Id, Status, NumberOfErrors, ExtendedStatus
FROM AsyncApexJob
WHERE Id = :jobId
];
System.debug(job.Status);The Status value is Queued, Preparing, Processing, Completed, Failed, or Aborted. A job that is still Queued right after you enqueue it is normal.
When to prefer Queueable over future
Choose Queueable in new code whenever you would have written a future method. It does everything a future method does, and it accepts richer arguments, returns an Id, and can be chained. Keep a future method only when you need to call it from a context that cannot enqueue a job, or when you are maintaining existing code that works.
Queueable is not designed for very large data sets. A single job is one transaction, so it has the same asynchronous limits as any other. Processing a million records in one execute method hits the CPU or heap limit. For volume, use Batch Apex, which a later chapter covers.
Exercise
A trigger on Contact must call an external API for every inserted contact. A teammate wrote for (Contact c : Trigger.new) { System.enqueueJob(new SyncJob(c)); }. A bulk load of 120 contacts fails. Why, and how do you fix it?
Show answer
The loop enqueues one job per record, and a synchronous transaction can enqueue at most 50 jobs, so the 51st call throws a LimitException. Collect the contact Ids into a Set<Id> inside the loop, then enqueue one SyncJob after the loop with the whole set. The job's constructor takes the Set<Id>, and its execute method re-queries the contacts (or processes them in sequence). The job class must also implement Database.AllowsCallouts for the HTTP call to be allowed.
Exercise
A Queueable job stores a List<Account> in a member variable and updates it 8 minutes after enqueueing. Users edit those accounts in the meantime. What can go wrong, and what do you change?
Show answer
The list is a snapshot from enqueue time, so the update can overwrite the users' newer edits with old field values. Store a Set<Id> instead and query the accounts inside execute so the job works on current data.