Vinod Sebastian – B.Tech, M.Com, PGCBM, PGCPM, PGDBIO

Hi I'm a Web Architect by Profession and an Artist by nature. I love empowering People, aligning to Processes and delivering Projects.

Advertisements




Salesforce Queueable Apex

Introduction

Salesforce Queueable Apex is an asynchronous Apex feature that allows you to offload non-urgent, long-running tasks to be processed in the background, reducing the load on the primary transaction thread. It is often used for tasks such as complex calculations, callouts to external systems, and other operations that do not need to be executed immediately.

Syntax

The syntax for defining a Queueable Apex class in Salesforce is as follows:

public class MyQueueableClass implements Queueable {
    public void execute(QueueableContext context) {
        // Implementation logic goes here
    }
}

Salesforce Queueable Apex Example

Let’s consider an example where we want to update a list of records asynchronously using Queueable Apex:

public class UpdateRecordsQueueable implements Queueable {
    List<Account> accountsToUpdate;

    public UpdateRecordsQueueable(List<Account> accounts) {
        this.accountsToUpdate = accounts;
    }

    public void execute(QueueableContext context) {
        update accountsToUpdate;
    }
}

Test Classes for Above Example

When writing test classes for Queueable Apex, you need to ensure that the Queueable job is executed synchronously so that you can assert the results. Here’s an example test class for the above Queueable Apex example:

@isTest
private class UpdateRecordsQueueableTest {
    @isTest
    static void testQueueableApex() {
        List<Account> testAccounts = new List<Account>();
        // Add test account records

        Test.startTest();
        UpdateRecordsQueueable queueable = new UpdateRecordsQueueable(testAccounts);
        System.enqueueJob(queueable);
        Test.stopTest();

        // Assert results
    }
}

Purpose

The main purpose of using Salesforce Queueable Apex is to ensure that long-running or non-urgent tasks do not impact the performance of the primary transaction. By offloading these tasks to be processed asynchronously, you can improve the overall efficiency and responsiveness of your Salesforce application.

Considerations

  • Queueable Apex jobs can be submitted from triggers, batch classes, Visualforce pages, or Lightning controllers.
  • Queueable jobs can be monitored and managed through the Apex Jobs page in Salesforce setup.
  • There are limits on the number of Queueable Apex jobs that can be queued and executed in a given transaction.
  • Queueable Apex jobs are resilient to governor limits and are ideal for handling complex processing requirements.