Sub topic 6
Chaining one job from another
A queueable job can start another queueable job from inside its own execute method. This is called chaining. This chapter covers how to do it, what the child job can and cannot see, and the mistakes that most often break a chain. This chapter assumes you can write a basic Queueable class and enqueue it with System.enqueueJob. It also assumes you know that each asynchronous job runs in its own transaction with its own governor limits. The exact numeric limits and the large-data pattern get their own chapters, so this chapter only touches them.
What chaining is
When a queueable job runs, Salesforce calls its execute method. Inside that method you can call System.enqueueJob again. The new job is the child, and the running job is the parent. The child is placed in the queue and runs later, in a new transaction, after the parent finishes.
Chaining is useful in three situations:
- Work must happen in a fixed order, and step two depends on step one having committed its data.
- One transaction cannot finish all the work within its limits, so you split it across several runs.
- A step needs a callout that cannot share a transaction with earlier uncommitted DML.
The child job is not called directly. The parent only asks the platform to schedule it, so the parent never receives the child's result. Anything the child needs must be passed in when you create it.
A two-step chain
The first job raises the rating on a set of accounts. When it finishes its DML, it enqueues a second job that creates a follow-up task for each account.
public class StepOneJob implements Queueable {
private List<Id> accountIds;
public StepOneJob(List<Id> accountIds) {
this.accountIds = accountIds;
}
public void execute(QueueableContext context) {
List<Account> accounts = [SELECT Id, Rating FROM Account WHERE Id IN :accountIds];
for (Account a : accounts) {
a.Rating = 'Warm';
}
update accounts;
if (!Test.isRunningTest()) {
Id childId = System.enqueueJob(new StepTwoJob(accountIds));
System.debug('Parent ' + context.getJobId() + ' enqueued child ' + childId);
}
}
}public class StepTwoJob implements Queueable {
private List<Id> accountIds;
public StepTwoJob(List<Id> accountIds) {
this.accountIds = accountIds;
}
public void execute(QueueableContext context) {
List<Task> tasks = new List<Task>();
for (Id accountId : accountIds) {
tasks.add(new Task(
Subject = 'Review new rating',
WhatId = accountId
));
}
insert tasks;
}
}Three details are worth noticing.
System.enqueueJobreturns the child's job ID.context.getJobId()returns the ID of the job that is currently running. Logging both lets you trace a chain later throughAsyncApexJob.- The enqueue call comes last. If an exception stops the parent before that line, no child is queued, so step two never runs against half-finished data.
- The
Test.isRunningTest()guard is explained in the testing section below.
The child gets a copy of the state
The child sees only what you hand it through its constructor. Static variables do not carry over, because the child runs in a different transaction, and probably on a different server. The same goes for local variables in the parent.
The member variables of the child are serialized when it is enqueued, then restored when it runs. This has consequences:
- The child works with a snapshot taken at enqueue time. If the parent changes a list after passing it, the child does not see the change.
- Pass IDs and small values, not large query results. A smaller job state is cheaper to store and avoids stale data. The child can query the current records itself, as
StepTwoJobcould. - Variables that cannot be serialized cause a failure at enqueue time. Mark such fields
transientand rebuild them insideexecute.
Chaining a job to itself
A job can also enqueue a new instance of its own class. This is how you repeat the same step with different input, or poll until a condition holds. The chunking chapter builds a full pattern on this. The shape is always the same:
public class RepeatingJob implements Queueable {
private Integer round;
public RepeatingJob(Integer round) {
this.round = round;
}
public void execute(QueueableContext context) {
// Do one round of work here.
if (round < 3 && !Test.isRunningTest()) {
System.enqueueJob(new RepeatingJob(round + 1));
}
}
}Always give a self-chaining job a stop condition that depends on its state. Without one, the job re-enqueues forever and uses up your asynchronous capacity.
One child per execute
The most common chaining error is trying to start more than one child from the same execute call. A running queueable may add only one new job to the queue. The second System.enqueueJob call throws a System.LimitException with a message such as Too many queueable jobs added to the queue: 2.
public void execute(QueueableContext context) {
System.enqueueJob(new StepTwoJob(accountIds));
System.enqueueJob(new StepThreeJob(accountIds)); // LimitException
}Instead, chain the jobs in a line. StepTwoJob enqueues StepThreeJob at the end of its own execute. This keeps the order explicit, and each job commits before the next starts.
The limit is different when you enqueue from synchronous code such as a trigger or an anonymous Apex block. There you can queue many jobs in one transaction, up to a per-transaction cap. Limits for both contexts, and for chain depth, are covered in the next chapter.
Failures in a chain
Each job in a chain is independent once it starts. Know these rules:
- If the parent throws an unhandled exception, its transaction rolls back. Treat the enqueue as part of that transaction, which is another reason to enqueue last.
- If the parent succeeds and the child later fails, the parent's committed changes stay. The chain stops at the failed job, and nothing automatically continues or undoes earlier steps.
- Nothing tells the parent that the child failed. To react to a failure, attach a finalizer to the job. Finalizers are covered later in the tutorial.
Because earlier steps cannot be rolled back, design each step so that running it twice does no harm. Setting a rating to Warm is safe to repeat. Inserting a task is not, since a repeated run creates a duplicate. When a step is not safe to repeat, store a marker such as a flag field or an external ID, and check it before inserting.
Chaining and callouts
A chain is the standard way to put a callout after DML. A transaction that has uncommitted DML cannot make a callout, and a transaction that has made a callout cannot always do DML afterward in the same context. Splitting the work into two jobs separates them cleanly. The job that makes callouts must implement Database.AllowsCallouts as well as Queueable.
public class NotifyJob implements Queueable, Database.AllowsCallouts {
public void execute(QueueableContext context) {
// Callout to an external system goes here.
}
}Chaining in tests
Apex tests do not support real chains. When Test.stopTest() runs the queued job, that job may not enqueue a child, and the attempt fails with a stack depth error. That is why each example above wraps its chaining call in !Test.isRunningTest().
The guard has a cost. The chaining line is skipped in tests, so a test never proves that the child gets enqueued. Test the parent and child separately: run each job's execute logic on its own and assert the results. The testing chapter shows the full approach.
Common mistakes
| Mistake | What happens | Fix |
|---|---|---|
| Two `System.enqueueJob` calls in one `execute` | `System.LimitException` in the second call | Chain one job after another in a line |
| Relying on a static variable set in the parent | The child sees the default value | Pass the value through the constructor |
| Self-chaining with no stop condition | The job re-enqueues without end | Test a counter or an empty list before enqueuing |
| Enqueuing before the DML that the child depends on | The child may start against missing data | Do the DML first and enqueue last |
| Forgetting `Database.AllowsCallouts` | Callout fails at runtime | Add the marker interface to the class that calls out |
| Chaining inside a test with no guard | Stack depth error in the test | Guard the call or test each job on its own |
Exercise
A queueable's execute method needs to start two independent follow-up jobs, FollowUpA and FollowUpB. It calls System.enqueueJob for each one and gets a LimitException on the second call. Why does this happen, and how would you restructure the code so that both jobs still run?
Show answer
A running queueable can add only one child job to the queue, so the second enqueue call throws. Restructure it as a line: the parent enqueues FollowUpA, and FollowUpA enqueues FollowUpB at the end of its own execute method, passing along any state FollowUpB needs through the constructor. Each job then runs in its own transaction, in a fixed order.
Exercise
StepOneJob updates accounts and then enqueues StepTwoJob, passing the same List<Id> it received. Why is it better to pass the IDs and let StepTwoJob query the records than to pass the queried Account records?
Show answer
The child receives a serialized snapshot taken at enqueue time. Account records passed in would be a copy that can be stale by the time the child runs, and large records make the job state bigger. Passing IDs keeps the state small, and the child's own query returns the current field values.