Saturday, December 25, 2021

Queueable Apex In Salesforce

Queueable Apex in Salesforce is similar to the Future Method in Salesforce, i.e., both are queued for execution. However, Queueable Apex provides additional benefits. This interface enables us to add jobs to the queue and monitor them. Using this interface is an enhanced way of running our asynchronous Apex code compared to using the Future Method.

Queueable Apex Syntax:

We need to implement Apex Class with Queueable Interface as shown below. Note that the queueable interface has only one method, which is the execute method.

public class QueueableApexExample implements Queueable {

    public void execute(QueueableContext context) {

        // code here

    }

}

To add the above class as a job on the queue,

ID jobID = System.enqueueJob(new QueueableApexExample ());

To query information about the above submitted job, we can perform a SOQL query on the AsyncApexJob object as shown below.

AsyncApexJob jobInfo = [SELECT Status,NumberOfErrors FROM AsyncApexJob WHERE Id=:jobID];

Benefits of using Queueable Apex:

1) When we submit our job by invoking the System.enqueueJob method, the method returns the ID of the new job. This ID corresponds to the ID of the AsyncApexJob record. We can use this ID to identify our job and monitor its progress, either through the Salesforce user interface in the Apex Jobs page or programmatically by querying your record from AsyncApexJob.

2) Our queueable class can contain member variables of non-primitive data types, such as sObjects or custom Apex types.

3) We can chain one job to another by starting a second job from a running job. Chaining jobs is useful if our process depends on another process to run first.

Queueable vs Future Methods in Salesforce

1) Queueable is an interface, whereas Future is a method.

2) The future method always requires IDs as a parameter. Objects are not allowed in the future method because there is a possibility that when the future method runs, i.e., when resources are available to it, the user might have changed the data inside the database, which can lead to processing the wrong data, whereas queueable can also contain non primitives data types and fetch data from the database again before making any updates, thus avoiding the wrong data getting inserted inside the database.

Queueable vs Batch Apex

1) Batch Apex is used for long-running jobs with large data volumes that need to be performed in batches, such as database maintenance jobs. Only use Batch Apex if you have more than one batch of records. If you don't have enough records to run more than one batch, you are probably better off using Queueable Apex.

2) Apex processes that run for a long time and include extensive database operations or external web service callouts can be run asynchronously by implementing the Queueable interface and adding a job to the Apex job queue. In this way, our asynchronous Apex job runs in the background in its own thread and doesn’t delay the execution of our main Apex logic.

3) Limitations of Batch Apex:

Up to 5 batch jobs can be queued or active concurrently.

Future methods are not allowed and cannot be called from Batch Apex.

4) Limitations of Queueable Apex:

Queueable can’t handle millions of records in one job.

Only one job can be scheduled at a time.

Reasons to use Queueable Apex over Batch Apex are as below:

1) A queueable apex can be called from the Future or Batch class.

2) In queueable apex, we can chain up to 50 jobs, whereas in batch apex, five concurrent jobs are allowed to run at a time. However, starting with API version 26.0, you can start another batch job from an existing batch job to chain jobs together. Chain a batch job to start a job after another one finishes and when your job requires batch processing, such as when processing large data volumes. Otherwise, if batch processing isn’t needed, consider using Queueable Apex.

Reasons to use Batch Apex over Queueable

It allows the processing of up to 50 million records.

Let’s understand the use of queueable apex with a real time scenario as explained below.

The "updateAccountIndustry" class is a Salesforce Apex queueable class designed to update the Industry field of a list of Account records with a specified industry value. It implements the Queueable interface, allowing it to be enqueued for asynchronous processing. The class takes a list of Account records and a target industry as parameters during instantiation. In the execute method, it iterates through the provided Account records and updates their Industry field with the specified industry value. The class is then enqueued for processing, making it suitable for handling updates to a large number of Account records in a scalable and asynchronous manner. In the provided example, it is used to update the Industry field for all accounts with a specific Type ("Technology Partner") in a separate asynchronous job.

public class updateAccountIndustry implements Queueable {

    private List<Account> accounts;

    private String accountsIndustry;

    public updateAccountIndustry(List<Account> records, String accIndustry) {

        this.accounts = records;

        this.accountsIndustry = accIndustry;

    }

    public void execute(QueueableContext context) {

        for (Account account : accounts) {

          account.Industry = accountsIndustry;

        }

        update accounts;

    }

}

// You can copy paste the below code in execute anonymous window

String accType='Technology Partner';

List<Account> accounts = [select id from account where Type =:accType];

String accIndustry='Communications';

// instantiate a new instance of the Queueable class

updateAccountIndustry updateAcc = new updateAccountIndustry(accounts, accIndustry);

// enqueue the job for processing

ID jobID = System.enqueueJob(updateAcc);

AsyncApexJob obj=[SELECT Id, Status, NumberOfErrors FROM AsyncApexJob WHERE Id = :jobID];

system.debug('Job Status'+obj.status);

No comments:

Post a Comment