Queueable Apex Chaining in Salesforce (Complete Guide with Examples & Best Practices)

In Salesforce, handling large data processing and long-running operations can be challenging using synchronous Apex.

To solve this problem, Salesforce provides asynchronous processing options like Future methods, Batch Apex, and Queueable Apex.

Among these, Queueable Apex is widely used because it offers greater flexibility, supports complex data types, and enables job chaining.

The queueable apex is a type of asynchronous apex in Salesforce that provides mechanisms to handle complex business logic.

It extends the capabilities of Future methods by allowing job chaining, monitoring, and passing complex data types.

In this tutorial, we will learn about queueable apex chaining in Salesforce with examples. In this, I will explain what queueable apex is, how to chain it in Salesforce, its methods, and how to execute it.

What is Queueable Apex in Salesforce?

Queueable Apex is an asynchronous Apex feature that allows you to run jobs in the background.

The queueable apex is an asynchronous processing method that allows us to run jobs in the background without blocking the execution of the primary transaction.

It is useful for executing long-running tasks, such as API callouts, complex calculations, and batch operations.

Key Features:

  • Runs asynchronously
  • Supports complex data types (like sObjects)
  • Allows monitoring using Job ID
  • Supports chaining

Advantages of Queueable Apex Over Future Methods

  • Job chaining: We can add another job from an existing queueable job.
  • Monitoring: The queueable jobs we can check on the Apex Jobs page. It can also be tracked.
  • Passing complex objects: Queueable apex supports non-primitive data types, including custom objects and list collections, unlike future methods.

Queueable vs Future vs Batch Apex

FeatureQueueableFutureBatch
Supports chainingYesNoNo
Supports complex dataYesNoYes
Best forMedium tasksSimple asyncLarge data

Syntax: Declaring Queueable Apex

public class Class_Name implements Queueable {
           public void execute( QueueableContext qc ) {
                   //logic;
       }
}

The apex class implements a queueable interface used for asynchronous processing. A class implementing queueable must define the execute() method.

Unlike @future methods, queueable allows job chaining for better control over async operations.

How to Execute Queueable Apex?

To execute queueable apex, we have to use the system.enqueueJob() method. We can execute from the Execute Anonymous Window in the Developer Console.

Syntax: To Execute Queueable Apex

To execute queueable Apex, we use System.enqueueJob. We can execute from the Execute Anonymous window in the Developer Console.

system.enqueueJob( new Class_Name());

What is Queueable Apex Chaining?

In Queueable Apex, chaining is the process of calling one Queueable job from another.

Inside the execute method, another queueable job is enqueued using System.enqueueJob(new AnotherQueueable()), ensuring sequential execution.

This process continues, forming a chain of queueable jobs in which each job starts only after the previous one completes.

This allows you to:

  • Break large processes into smaller jobs
  • Execute jobs sequentially
  • Avoid governor limits

Example: Queueable Apex Chaining in Salesforce

Let’s take a scenario: we want to process a list of accounts with an account priority of ‘High’ to update their contact description and then send notification emails.

So, we know it has multiple logics to develop, and combining all of them into a single logic would lead to complex, unmanageable code.

Hence, we will break this into separate apex classes to improve readability and make it more manageable.

As per the scenario, we want to achieve three different functionalities. So, a separate queueable class will represent each step, and we will chain them together to achieve the workflow.

  • Processing the list of accounts
  • Updating the associate contacts description
  • Send Notification emails

Processing list of Accounts

In this step, we will create a queueable apex class to fetch and process a list of accounts. Once processed, this class will chain to the next job to update contacts.

We created a class that implements the queueable interface. Then, in the execute() method, we declared a list to retrieve accounts with high priority.

Then using enqueueJob() method a new queueable job, UpdateContactsForAccounts (class), is enqueued. We will update the contact description in the class we create, and the fetched accounts will be passed to this job for further processing.

public class FetchAndProcessAccounts implements Queueable {
           public void execute(QueueableContext context) {
                   List<Account> accounts = [SELECT Id, Name,Account_Priority__c FROM Account   
                                                                    WHERE Account_Priority__c = 'High'];
                   System.enqueueJob(new UpdateContactsForAccounts(accounts));
            }
}

Now, navigate to the account object and open the record. The account priority is high. Here is a high-priority account.

Salesforce Queueable Apex

Updating Associate Contacts

In this step, we will create a class that implements the queueable interface for asynchronous processing and update the contacts associated with the accounts processed in the previous step.

After that, declare a private list to store the accounts received from the previous queueable job (FetchAndProcessAccounts). Then, a constructor must accept a list of account records when enqueued.

Then, in the execute() method, we will implement the logic that runs when the queueable job is executed. In this method, we declare a set to store the account IDs from our list. Then, using the for loop, add IDs to the set variable.

After that, we updated the description field on the contact object for related contacts, and the enqueueJob() method chains another queueable job class (SendNotificationEmails) after updating the contacts.

The enqueueJob() method passes the list of updated contacts to the SendNotificationEmails queueable job. This ensures that after contacts are updated, notification emails are sent asynchronously.

public class UpdateContactsForAccounts implements Queueable {
    private List<Account> accounts;
    
    public UpdateContactsForAccounts ( List<Account> accounts ) {
        this.accounts = accounts;
    }
    
    public void execute ( QueueableContext context ) {
        Set<Id> accountIds = new Set<Id>();
        for (Account acc : accounts) {
            accountIds.add(acc.Id);
        }

        List<Contact> contacts = [SELECT Id, Email,Description FROM Contact WHERE 
                                                                  AccountId IN :accountIds];

        for (Contact con : contacts) {
            con.Description = 'Belongs to High Priority Account';
        }

        update contacts;
        System.enqueueJob(new SendNotificationEmails(contacts));
    }
}

We have two contacts for the selected account, and after executing the code above on both accounts, the description field should be updated to the message specified in the code.

Queueable Apex in Salesforce

In the image below, you can see that the description field is empty. After executing the queueable apex, this should automatically display the message ‘Belongs to High Priority Account.’

Queueable Apex Chaining in Salesforce

Send Notification Email

In this final step, we will create a class that implements a queueable interface to send notification emails to the contacts updated in the previous step.

Declare a private list of contacts to store those who will receive notification emails. Then, in the constructor, accept the list of contact records.

After that, declare the execute() method, where we will implement the logic for asynchronously sending emails to contacts.

In this method, we will initialise a list to store multiple email messages. Then create a new email message object to access the email attributes.

Now set the values for email attributes such as the recipient email, subject, and email body. After that, add this message (including all information) to the list we created to store email messages.

Then send all emails in bulk using Messaging.sendEmail(). This ensures efficient email processing and respects Salesforce governor limits.

Now save the code and execute the

public class SendNotificationEmails implements Queueable {
    private List<Contact> contacts;
    
    public SendNotificationEmails( List<Contact> contacts ) {
        this.contacts = contacts;
    }
    public void execute( QueueableContext context ) {
        List<Messaging.SingleEmailMessage> emails = new 
                                                                        List<Messaging.SingleEmailMessage>();

        for (Contact con: contacts) {

            Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
            email.setToAddresses( new String[] { con.Email } );
            email.setSubject( 'High Priority Account' );
            email.setPlainTextBody( 'Congractulations...! Your account is promotes to High 
                                                                     Priority.' );
            emails.add(email);
        }

        Messaging.sendEmail(emails);
    }
}

Now, let’s understand the flow of queueable chaining apex classes that we created:

  1. FetchAndProcessAccounts -> Fetches inactive accounts and enqueues UpdateContactsForAccounts.
  2. UpdateContactsForAccounts -> Updates contact records and enqueues SendNotificationEmails.
  3. SendNotificationEmails -> Sends notification emails to contacts.

Execute the Queueable Apex Chaining Code

We can enqueue the first job from an Apex trigger, a button click, or a scheduled job to initiate the chain of queueable jobs. So, here I have explained how to start the queueable chain from the developer console.

To start the process, we need to run the first queueable class, FetchAndProcessAccounts. To do so, open an anonymous window and run the code below.

System.enqueueJob( new FetchAndProcessAccounts());

Output

After executing the queueable apex chaining class, navigate to the contact associated with the high-priority account and check the description field. There, you will see the description that you provided in the update contact class.

Salesforce Queueable Apex Chaining Class

Also, we received the email with the values that we provided in the SendNotificationEmails class.

Implement Queueable Interface in Salesforce Apex

In this way, we can implement queueable apex chaining in Salesforce to execute long-running tasks.

Conclusion

Queueable Apex Chaining is a powerful feature in Salesforce that allows developers to execute asynchronous jobs in a sequence. It helps in handling large data processing, avoiding governor limits, and improving application performance.

I hope you now have an idea about queueable apex chaining in Salesforce. In this, I have explained what queueable apex is, how to chain it in Salesforce, its methods, and how to execute it.

In the example, I demonstrate a practical implementation of queueable apex chaining to process accounts, update associated contacts, and send notification emails. I create different classes to enhance code maintainability, scalability, and performance.

You may like to read:

Agentforce in Salesforce

DOWNLOAD FREE AGENTFORCE EBOOK

Start with AgentForce in Salesforce. Create your first agent and deploy to your Salesforce Org.

Salesforce flows complete guide

FREE SALESFORCE FLOW EBOOK

Learn how to work with flows in Salesforce with 5 different real time examples.