Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 36 ยท Asynchronous Apex

Queueable Apex: Chaining, Job Ids and Finalizers

Learn Queueable Apex: implement the interface, pass sObjects, chain jobs, track the job Id and use finalizers, with Apex listings and a runnable Java job-chain stand-in.

Queueable Apex is the modern replacement for most @future methods. You write a class that implements Queueable, pass it to System.enqueueJob, and the platform runs its execute method in the background. Unlike future methods, a queueable job can hold sObjects and other complex state in member variables, returns a job Id you can monitor, and can start another job when it finishes. It builds on future methods.

Apex runs only in an org. The Apex listings below are read-only; the runnable examples are Java stand-ins for the queue and chain behaviour.

A first queueable job

APEX
public with sharing class RatingJob implements Queueable {
    private List<Id> accountIds;

    public RatingJob(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 = 'Hot';
        }
        update accounts;
    }
}

Enqueue it from anywhere:

APEX
Id jobId = System.enqueueJob(new RatingJob(new List<Id>{ acct.Id }));

jobId is an AsyncApexJob record Id. You can query it (SELECT Status, NumberOfErrors FROM AsyncApexJob WHERE Id = :jobId) or see it under Setup, Apex Jobs.

State passed through the constructor is serialised and restored, so you may keep List<Account>, maps and your own serialisable classes. Fields that cannot be serialised should be marked transient.

Callouts from a queueable

To make HTTP callouts also implement Database.AllowsCallouts:

APEX
public class ErpPushJob implements Queueable, Database.AllowsCallouts {
    public void execute(QueueableContext ctx) {
        // build HttpRequest and call new Http().send(req)
    }
}

Chaining jobs

From inside execute you may enqueue one more job. This is how you split a long process into steps, or loop through pages of work where each step needs the previous one to finish.

APEX
public class StepOneJob implements Queueable {
    public void execute(QueueableContext ctx) {
        // ... first step
        System.enqueueJob(new StepTwoJob());
    }
}

Rules to remember:

  • A transaction may enqueue up to 50 queueable jobs, but from within a running queueable job you may enqueue only one child.
  • In production, chain depth is effectively unlimited. In Developer Edition and trial orgs the depth is limited to 5, so chain tests with care.
  • Tests cannot chain: calling System.enqueueJob in an execute that is itself running inside a test throws an error unless you guard it with if (!Test.isRunningTest()), or use System.AsyncInfo to detect the situation. A typical pattern is to chain only when Test.isRunningTest() is false.
  • Use a unique-by-key guard to avoid duplicate jobs. System.enqueueJob(job, new AsyncOptions()) accepts options such as DuplicateSignature to stop identical jobs from being queued twice.

Finalizers

A finalizer runs after the job finishes, whether it succeeded or failed, and may enqueue a retry or log the error. Attach it inside execute:

APEX
public class SafeJob implements Queueable {
    public void execute(QueueableContext ctx) {
        System.attachFinalizer(new LogFinalizer());
        // risky work here
    }
}

public class LogFinalizer implements Finalizer {
    public void execute(FinalizerContext ctx) {
        if (ctx.getResult() == ParentJobResult.UNHANDLED_EXCEPTION) {
            System.debug('Job failed: ' + ctx.getException().getMessage());
        }
    }
}

Finalizers are the reliable way to learn about an uncaught exception, because the failed job cannot catch its own limit exceptions.

Testing

APEX
@isTest
static void ratingJobMarksAccountsHot() {
    Account a = new Account(Name = 'Queue Co');
    insert a;

    Test.startTest();
    System.enqueueJob(new RatingJob(new List<Id>{ a.Id }));
    Test.stopTest();

    Assert.areEqual('Hot', [SELECT Rating FROM Account WHERE Id = :a.Id].Rating);
}

Try the idea: a job with state (Java stand-in)

Java Stand-in: queued jobs carry their own state and return a job Id (Java)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Try the idea: chaining and a finalizer (Java stand-in)

Java Stand-in: a chain of jobs and a finalizer (Java)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Each job enqueues exactly one child, mirroring the real rule, and the finalizer reports the failure after the job ends.

Queueable or batch?

Queueable is great for tens to a few thousand records and for ordered steps. For millions of rows, or when you need automatic chunking with a fresh set of limits per chunk, use Batch Apex.

flowchart LR
    A["Trigger or class"] -->|"System.enqueueJob"| B["Queue"]
    B --> C["execute()"]
    C -->|"enqueue one child"| B
    C --> D["Finalizer"]

A queueable job can add one child to the queue and attach a finalizer that always runs afterwards.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does System.enqueueJob return?

    It returns the Id of the AsyncApexJob record, which you can query to monitor the job.
  2. 2. How many child jobs may a running queueable enqueue?

    From inside execute you can chain exactly one more job; from a normal transaction you can enqueue up to 50.
  3. 3. Which interface do you add to make HTTP callouts from a queueable?

    Database.AllowsCallouts marks the class as allowed to make callouts; HttpCalloutMock is only for tests.
  4. 4. What is a finalizer for?

    A finalizer runs after the queueable completes, so it can log errors or retry even when the job failed with an unhandled exception.

Summary

  • Implement Queueable, enqueue with System.enqueueJob, and keep the state in member variables.
  • Add Database.AllowsCallouts for HTTP.
  • Chain one child per job; attach finalizers for failure handling.
  • Prefer queueable to @future for new code; use batch for very large volumes.

Next: Batch Apex