+ Start a Discussion
Raj R.Raj R. 

How to call queueable class from trigger?

Hi,

We have a need to call a queueable apex class from a trigger after insert. Would it be possible to do the following below as we need to also do chaining? We need to perform updates to different objects in consecutive order so wanted to use a queue. 
trigger SomeTrigger on CustomObject__c (after insert) {
       System.enqueuejob(new  QueueClass1(Trigger.new))
}

public class QueueClass1 implements Queueable {
              private List<CustomOBject__c> objs;
              
              public QueueClass1(List<CustomObject> recs) {
                            this.objs = recs;
              }
              
               public void execute(QueueableContext queCont) {
                            //execute some logic on objs list
                            //perform update

                          //call second queueable apex job
                         System.enqueueJob(new QueueClass2(recs));
               }

}

public class QueueClass2 implements Queueable {
              private List<CustomOBject__c> objs;
              
              public QueueClass2(List<CustomObject> recs) {
                            this.objs = recs;
              }
              
               public void execute(QueueableContext queCont) {
                            //execute other logic on objs list
                            //create records for another objects
                            List<Account> acnts; //acnts list is populated based on logic executed in the "other logic"
                             insert acnts;
               }

}

 
Best Answer chosen by Raj R.
@GM@GM
Hi,

are you getting any errors? I just called Queueable job from trigger & its working as expected but not sure about chaining.

trigger LeadTrigger on Lead(before insert) {
if(Trigger.isBefore){
if(Trigger.isInsert){
System.enqueueJob(new QueueableExample(Trigger.New));
}
}
}

All Answers

@GM@GM
Hi,

are you getting any errors? I just called Queueable job from trigger & its working as expected but not sure about chaining.

trigger LeadTrigger on Lead(before insert) {
if(Trigger.isBefore){
if(Trigger.isInsert){
System.enqueueJob(new QueueableExample(Trigger.New));
}
}
}
This was selected as the best answer
Gangadhar LGangadhar L
Hi @Raj R and @GM,
If you provide test class for this code. it will be great helpful for me. I'm facing some problem in test class for this code.