Queueable Apex Salesforce

Queueable Apex Salesforce

Queueable Apex Salesforce is more advanced and enhanced version of future methods with some extra features.  It has simplicity of future methods and the power of Batch Apex and mixed them together to form Queueable Apex. It gives you a class structure that the platform serializes for you, a simplified interface without start and finish methods and even allows you to utilize more than just primitive arguments! It is called by a simple System.enqueueJob() method, which returns a job ID that you can monitor.  We need to implement Queueable interface for performing queueable operation.

Queueable Apex Salesforce

Advantage of using queueable Apex

Queueable jobs are similar to future methods in that they’re both queued for execution, It has following benefit compared to future methods:

  • Getting an ID for your job: 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 job and monitor its progress, either through the Salesforce user interface in the Apex Jobs page, or programmatically by querying your record from AsyncApexJob.
  • Using non-primitive types: Your queueable class can contain member variables of non-primitive data types, such as sObjects or custom Apex types. Those objects can be accessed when the job executes.
  • Chaining jobs: You can chain one job to another job by starting a second job from a running job. Chaining jobs is useful if you need to do some processing that depends on another process to have run first.

Queueable Versus Future

Because queueable methods are functionally equivalent to future methods, most of the time you’ll probably want to use queueable instead of future methods. However, this doesn’t necessarily mean you should go back and refactor all your future methods right now. If you were exceeding a governor limit in your future method, or if you think a future method requires a higher limit, you can possibly increase the limits for your future method with the Future Methods with Higher Limits pilot.

Another reason to use future methods instead of queueable is when your functionality is sometimes executed synchronously, and sometimes asynchronously. It’s much easier to refactor a method in this manner than converting to a queueable class. This is handy when you discover that part of your existing code needs to be moved to async execution.

Queueable Apex Syntax

We need to implement Apex Class with Queueable Interface which contains only one method execute. We also need to implement DatabaseAllowsCallouts in case if you wanted to process the callouts from the Queueable apex.

public class SomeClassName implements Queueable { 
    public void execute(QueueableContext context) {
        // awesome code here
    }
}

Execute Queueable Apex

Execute the Queueable apex with  System.enqueueJob method which will return the job Id. Once you enqueue a new job, you get a job ID that you can actually monitor from the ApexJobs sections or by using AsyncApexJob object.

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

Queueable Apex Example

In this example we will append sfdcpoint at the end of account name

public class AccountQueueableExample implements Queueable {
    public List<Account> accList ; 
    public AccountQueueableExample(List<Account> accList){
        this.accList = accList ;  
    }
    public void execute(QueueableContext context) {
        for(Account acc :accList){
            // Update the Account Name 
            acc.Name = acc.Name + 'sfdcpoint';
        }
        update accList;
    }
}

Run the job from the execute anonymous with below code

List<Account> accList = [Select Id , Name from Account ];
ID jobID = System.enqueueJob(new AccountQueueableExample(accList));
System.debug('jobID'+jobID);

Test class for Queueable Apex

@isTest
public class AccountQueueableExampleTest {
    @testSetup 
    static void setup() {
        List<Account> accounts = new List<Account>();
        // add 100 accounts
        for (Integer i = 0; i < 100; i++) {
            accounts.add(new Account(
                name='Test Account'+i
            ));
        }
        insert accounts;
    }
    
    static testmethod void testQueueable() {
        // query for test data to pass to queueable class
        List<Account> accounts = [select id, name from account where name like 'Test Account%'];
        // Create our Queueable instance
        AccountQueueableExample accQObj = new AccountQueueableExample(accounts);
        // startTest/stopTest block to force async processes to run
        Test.startTest();        
        System.enqueueJob(accQObj);
        Test.stopTest();        
        // Validate the job ran
        System.assertEquals(100, [select count() from account where Name like = '%sfdcpoint%']);
    }
    
}

Queueable Job chaining

One of the best features of Queueable Apex is job chaining. If you ever need to run jobs sequentially, Queueable Apex could make your life much easier. To chain a job to another job, submit the second job from the execute() method of your queueable class. You can add only one job from an executing job, which means that only one child job can exist for each parent job. For example, if you have a second class called SecondJob that implements the Queueable interface, you can add this class to the queue in the execute() method as follows:

 
public class FirstJob implements Queueable { 
    public void execute(QueueableContext context) { 
        // Awesome processing logic here    
        // Chain this job to next job by submitting the next job
        System.enqueueJob(new SecondJob());
    }
}

Queueable Apex limits

Queueable Apex is a great new tool but there are a few things to watch out for:

  • The execution of a queued job counts once against the shared limit for asynchronous Apex method executions.
  • You can add up to 50 jobs to the queue with System.enqueueJob in a single transaction.
    When chaining jobs, you can add only one job from an executing job with System.enqueueJob, which means that only one child job can exist for each parent queueable job. Starting multiple child jobs from the same queueable job is a no-no.
  • No limit is enforced on the depth of chained jobs, which means that you can chain one job to another job and repeat this process with each new child job to link it to a new child job. However, for Developer Edition and Trial orgs, the maximum stack depth for chained jobs is 5, which means that you can chain jobs four times and the maximum number of jobs in the chain is 5, including the initial parent queueable job.

 

For more details about Queueable Apex please refer to Control Processes with Queueable Apex  trailhead

Permanent link to this article: https://www.sfdcpoint.com/salesforce/queueable-apex-salesforce/

Leave a Reply

Your email address will not be published.