Queueable Apex

Queueable Apex is the simplicity of Future Apex and power of Batch Apex.
To write a Queueable apex class you have to implement Queueable Interface. It provides a class structure that doesn't need start and finish method like Batch Apex. you can call apex class by using a simple method called System.enqueue(). This method returns a job Id by which you can monitor it.


Queueable Syntax--

public class ClassName implements Queueable{

          public void execute(QueueableContext QC){
       
                 //your awesome logic
          }
}

Example-

For example, we create a Queueable Apex class that insert contacts for Account

Apex Class--

 public class AddPrimaryContact implements Queueable{

    private Contact ct;
    private String st;
 
    public AddPrimaryContact(Contact ct,String state){
        this.ct = ct;
        this.st = state;
    }
 
    public void execute(QueueableContext context){
   
       List<Account> accs = [SELECT ID, Name ,(Select id,FirstName,LastName from contacts ) FROM ACCOUNT WHERE BillingState = :st LIMIT 200];
       List<Contact> con = new List<Contact>();
       for(Account ac : accs){
       
           Contact c = ct.clone(false,false,false,false);
           c.AccountId = ac.Id;
           con.add(c);
       }
       if(con.size()>0){
           insert con;
       }
    }
}

Test Class-->

@isTest
public class AddPrimaryContactTest{
 
    public static testMethod void positiveScenario(){
 
        List<Account> acc = new List<Account>();
        for(Integer i=0; i<50; i++){
            acc.add(new Account(Name ='Tom'+i,BillingState ='NY'));
        }
     
        for(Integer i=0; i<50; i++){
            acc.add(new Account(Name ='Tom'+i,BillingState ='CA'));
        }
        insert acc;
     
        Contact c = new Contact();
        c.FirstName = 'Huen';
        c.LastName = 'Patt';
        insert c;
        String state = 'CA';
     
     
        AddPrimaryContact apc = new AddPrimaryContact(c,state);
        Test.startTest();
        System.enqueueJob(apc);
        Test.stopTest();
    }
}

Comments

Popular posts from this blog

How to show or hide a particular section of Visualforce Page dependent upon picklistfield value

Process Automation Specialist Superbadge

Dynamically Add/Delete rows in Visualforce Page