Sub topic 2
Limits That Apply to Enqueuing and Chaining
Assume you know basic Apex classes, SOQL, DML, and governor limits. These limits matter because each asynchronous job runs in its own transaction with fresh limits.
Enqueue and chain limits
A synchronous transaction can enqueue up to 50 queueable jobs. An asynchronous transaction, such as a queueable's execute method, can enqueue only one queueable job. This rule makes a queueable chain linear unless you deliberately create work elsewhere.
A queueable can enqueue its child after it finishes processing. The child receives only the state that you pass to its constructor. Keep that state small because Salesforce serializes it between transactions.
public class AccountChunkJob implements Queueable {
private static final Integer CHUNK_SIZE = 200;
private List<Id> remaining;
public AccountChunkJob(List<Id> remaining) {
this.remaining = remaining;
}
public void execute(QueueableContext context) {
Integer count = Math.min(CHUNK_SIZE, remaining.size());
List<Id> current = remaining.subList(0, count);
List<Id> rest = remaining.subList(count, remaining.size());
List<Account> accounts = [
SELECT Id, Description
FROM Account
WHERE Id IN :current
];
for (Account account : accounts) {
account.Description = 'Processed';
}
update accounts;
if (!rest.isEmpty() && !Test.isRunningTest()) {
System.enqueueJob(new AccountChunkJob(rest));
}
}
}Processing a large list in slices
Chunking means dividing a large input into smaller lists. Each job handles one slice and enqueues one child for the remaining IDs. This limits heap use, query rows, and DML rows in each transaction.
Controlling chains with AsyncOptions
AsyncOptions can limit chain depth, delay execution, and reject duplicate jobs. A duplicate signature helps prevent two equivalent jobs from running at the same time.
AsyncOptions options = new AsyncOptions();
options.MaximumQueueableStackDepth = 3;
options.MinimumQueueableDelayInMinutes = 2;
options.DuplicateSignature = QueueableDuplicateSignature.Builder()
.addString('AccountRatingJob')
.build();
System.enqueueJob(new AccountChunkJob(accountIds), options);Attaching a transaction finalizer
A finalizer runs after the queueable transaction completes. Attach one from execute. It can inspect whether the parent succeeded or failed and can enqueue a bounded retry.
public class ImportJob implements Queueable {
public void execute(QueueableContext context) {
System.attachFinalizer(new ImportFinalizer());
// Perform import work here.
}
}
public class ImportFinalizer implements Finalizer {
public void execute(FinalizerContext context) {
if (context.getResult() == ParentJobResult.FAILURE) {
System.debug(LoggingLevel.ERROR,
'Failed job: ' + context.getAsyncApexJobId());
}
}
}Exercise
How many queueable jobs can an asynchronous transaction enqueue?
Show answer
One.