Our Blog

Queueable Apex in Salesforce

Queueable Apex in Salesforce

Queueable Apex in Salesforce

Queueable Apex in Salesforce allows you to submit jobs for asynchronous processing similar to future methods.

To make a Class queueable we have to implement the Queueable interface. class and method implementation must be declared as public or global. By adding this interface we can add the job to the queue and monitor them by the going to apex job from quick find box or from job id

 

public class wkQueueableClass implements Queueable {

The interface has only one method execute which takes the parameter of QueableContext

public void execute(QueueableContext context) {
    // Your code here
}

To submit your class for asynchronous execution, call the System.enqueueJob by passing it an instance of your class implementation of the Queueable interface as follows

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

A queueable class can contain member variables of non-primitive data types, such as subjects or custom Apex types

 

Example

public class wkQueueableClass implements Queueable {
    public void execute(QueueableContext context) {
        Account wkacc = new Account(Name='Webkul');
        insert wkacc;        
    }
}

To add this class as a job on the queue, call this method:

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

This will add class in the queue for execution job is added to the queue and will be processed when system resources become available

 

The status of a job can be monitor programmatically by querying AsyncApexJob eg:-

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

 

Testing Queueable Jobs:

A queueable job is an asynchronous process. So first we have to be sure that this process runs within the test method, the job is submitted to the queue between the Test.startTest and Test.stopTest block.

@isTest
public class wkQueueableClassTest {
    static testmethod void test1() {
        // startTest/stopTest block to force async processes to run in the test.
    
        Test.startTest();        
        System.enqueueJob(new wkQueueableClass());
        Test.stopTest();
        
        Account acc = [SELECT Name,Phone FROM Account WHERE Name='webkul' LIMIT 1];
        System.assertNotEquals(null, acc);
    }
}




 

Limits:

  • we can add up to 50 jobs to the queue with System. enqueueJob in a single transaction.
  • we can chain one job to another Because no limit is enforced on the depth of chained jobs
  • When chaining jobs with System.enqueueJob, you can add only one job from an executing job

Leave a Comment

Comments (0)

Please verify that you are not a robot.

Welcome back

Welcome back! Please enter your details

One or more fields have an error. Please check and try again.

Forgot Password?

Tell us about Your Company

How can we help you with your business?