Queueable Apex Chaining in Salesforce With Examples : Bijay Kumar

Queueable Apex Chaining in Salesforce With Examples
by: Bijay Kumar
blow post content copied from  SalesForce FAQs
click here to view original post



### Summary of Queueable Apex Chaining in Salesforce **What is Queueable Apex?** Queueable Apex is an asynchronous processing method in Salesforce that allows you to perform complex tasks in the background without interrupting the main transaction. Unlike traditional future methods, it offers better flexibility through job chaining, monitoring, and the ability to handle complex data types, including custom objects. **Main Advantages:** 1. **Job Chaining:** You can initiate another job from an existing queueable job. 2. **Monitoring Capability:** Jobs can be tracked via the Apex Jobs page. 3. **Support for Complex Objects:** It allows for non-primitive data types, such as collections and custom objects. **How to Use Queueable Apex:** To declare a Queueable Apex class, you need to implement the `Queueable` interface and define the `execute()` method. The basic syntax is: ```apex public class Class_Name implements Queueable { public void execute(QueueableContext qc) { // Logic goes here } } ``` To execute a queueable job, use the following syntax in the Developer Console: ```apex System.enqueueJob(new Class_Name()); ``` **Chaining in Queueable Apex:** Chaining happens when a Queueable class enqueues another Queueable job within its `execute()` method. This enables you to create a sequence of jobs that execute one after the other. ### Example: Chaining Queueable Apex Jobs In this tutorial, you will create three different classes for processing accounts, updating contacts, and sending notification emails: 1. **FetchAndProcessAccounts:** Fetches high-priority accounts and enqueues the next job. 2. **UpdateContactsForAccounts:** Updates contact descriptions for the accounts processed earlier and enqueues the email notification job. 3. **SendNotificationEmails:** Sends emails to the contacts whose descriptions were updated. ### Execution Flow When executed, the jobs follow this sequence: - **FetchAndProcessAccounts** → **UpdateContactsForAccounts** → **SendNotificationEmails** You can start the queuing process using the Developer Console with: ```apex System.enqueueJob(new FetchAndProcessAccounts()); ``` **Testing the Output:** After running the above code, check the relevant contacts to confirm their descriptions have been updated and that notification emails have been sent. ### Conclusion Queueable Apex is a robust way to handle asynchronous processing in Salesforce. Through chaining, you can break down complex tasks into manageable segments, leading to improved maintainability and clarity in your code. ### Additional Information For further learning, consider exploring: - Scheduler Apex in Salesforce - Batch Apex in Salesforce - How to Call Apex Methods From LWC in Salesforce ### Hashtags for SEO #Salesforce #QueueableApex #AsynchronousProcessing #SalesforceDevelopment #ApexChaining #SalesforceTutorial #APIIntegrations #CloudComputing #SalesforceBestPractices #EnterpriseSolutions


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 that, I will explain what queueable apex is, chaining in queueable apex in Salesforce, their methods, and how to execute a queueable apex in Salesforce.

What is Queueable Apex in Salesforce?

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.

Queueable Apex provides the following advantages 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 also can be tracked.
  • Passing complex objects: Queueable apex supports non-primitive data types, including custom objects and list collections, unlike future methods.

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 have to use system.enqueueJob. We can execute from the Execute Anonymous window in the Developer Console.

system.enqueueJob( new Class_Name());

What is Chaining in Queueable Apex?

In Queueable Apex, chaining refers to the process where a queueable class implements the queueable interface and its execute method. 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 where each job starts only after the previous one is completed.

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, here we know it has multiple logic to develop, and building all these in one single logic would lead to a complex and unmanageable code.

Hence, we will break this into different apex classes to maintain its readability and make it more manageable.

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

  • Processing list of Account
  • 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 collection to get the accounts whose account priority is high.

Then using enqueueJob() method a new queueable job, UpdateContactsForAccounts (class), is enqueued. We will update the contact description in the class that we will create, and the fetched accounts will be passed on 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, we have a high-priority account.

Salesforce Queueable Apex

Updating Associate Contacts

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

After that, declare a private list of accounts 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 the set collection, which will 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 from the contact object for related contacts, and the enqueueJob() method chains another queueable job class(SendNotificationEmails) after updating 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 above code for both of these accounts, the description field should get updated to the declared message in the code.

Queueable Apex in Salesforce

In the below image, you can see 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 the contacts that 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 sending emails to contacts asynchronously. In this method, we will Initialize a list to store multiple email messages. Then, create the new email message object instance to access the email attributes.

Now, set the values for email attributes like recipient email, subject, and email body. After that, add this message (all information) to the list that we created to store the 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 execute the first queueable class, which is 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 that is related to 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 the queueable apex chaining in Salesforce when executing long-running tasks.

Conclusion

I hope now you have got an idea about queueable apex chaining in Salesforce. In that, I have explained what queueable apex is, chaining in queueable apex in Salesforce, their methods, and how to execute a queueable apex in Salesforce.

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:

The post Queueable Apex Chaining in Salesforce With Examples appeared first on SalesForce FAQs.


February 12, 2025 at 12:46PM
Click here for more details...

=============================
The original post is available in SalesForce FAQs by Bijay Kumar
this post has been published as it is through automation. Automation script brings all the top bloggers post under a single umbrella.
The purpose of this blog, Follow the top Salesforce bloggers and collect all blogs in a single place through automation.
============================

Salesforce