Salesforce Asynchronous Apex: How to Call Queueable Apex Class from a Trigger

 

Looking for Salesforce Training & HandsOn Projects?


Queueable Apex is just another flavor of Async Programming implementation offered by the Salesforce Platform. 

You can refer to my earlier posts on Queueable Job to get a context around this concept:

In this article, we will explore how to call a Queueable Job from within the Trigger. 

We can start with a simple demo to explain the concept in the following steps:   

Step-1: Create a brand new Apex Class to implement the Queueable Job.


Step-2: We need to define a Constructor to call the Queueable Job from a Trigger & pass on the list of records to operate on by the Job in an Async manner. 

Step-3: Now implement execute function & implement all the logic that you would like to execute asynchronously.

For this demo we are getting a list of Account from Trigger & for each Account we are creating 5 Contacts.



Step-4: Create a brand new Trigger.



Step-5: Give it a suitable name to the Trigger.



Step-6:  This Trigger will be on Accounts Object & it will be “After Insert” Event. 

The Queueable Job is being called from within the Trigger by using “System.enqueueJob” method by passing “Trigger.New” as input parameter to the constructor of the Queueable Apex Class. 

“Trigger.New” is representing the list of all Accounts inserted causing this Trigger to execute.

When the Trigger is fired, the “System.enqueueJob” method will enqueue the Queueable class. The Queueable class will then be executed asynchronously.



Step-7: Now we can test our code by adding a new Account. Go Account List Page, click on “New” Button.



Step-8: Add required details to create the Account & click on “Save” button



Step-9: Here we can see 5 new Contacts created for this Account on the Account Details Page



Step-10: We can validate the same by going to the Contacts List Page



Step-11: We can also refer to the debug logs & locate the log entries as per our logic



Here are some things to keep in mind when calling Queueable classes from triggers:

  •     You can only enqueue one Queueable class per trigger execution.
  •        You should only enqueue Queueable classes from triggers that are not frequently executed. If you enqueue a Queueable class from a trigger that is executed frequently, it could cause performance problems.

Hope you enjoyed this article. Please leave your comments to let me know how you like the content and how you find it helpful to learn the topic.

Comments