Too many queueable jobs added to the queue: 2

Prerequisites to understand about this error:
You need to be aware of 

When we will get this error? 
This error only occurs if we try to enqueue more than 1 Queueable Job from execute()/finish() method of Batch class in one transaction. We can submit only 1 job at a time(per Transaction).

Design-1 [which causes this error]:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Assume, in the Account object, we have 500 records. To initiate the batch class we can execute the below code snippet in execute anonymous block:


The batch size = 200.
Total no.of Transactions = 500/200 =3
Total no.of times "execute()" method will invoke =3.
Total no.of times "execute()" method will try to call the Queueable interface implemented class =200 times per transaction.

In the above code design, we will get the error because, per transaction, allowed enequedJobs =1.

Solutions for the above problem :
~~~~~~~~~~~~~~~~~~~~~~~~~~
Solution 1:
~~~~~~~
In the execute method check if already a job is submitted or not (Observe line# 11 as per the below code snippet)


The above solution is not appropriate because next records will not process. So, Let's get for the next best solution.
Solution2:
~~~~~~~
Let's bulkify the Queuable class and batch class.



Design-2 [which causes this error]:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1. Let's say I have a batch class on Account which will update the Account records.
2. I have a trigger on Account which will fire on Update operation.
3. The Account trigger will enqueue the Queueable job.
4. If we initiate the batch job from execute anonymous block or through the scheduled class with a batch size of more than 200 we will get this error.

Note: You might be thinking, batch job execute() method and Trigger will be executed in 2 different transactions(which is correct) then why we will get this error? because the source (data) for Trigger is coming from batch class execute() method that is the reason for this error.

code snippet :
~~~~~~~~~~

Solution :
If the batch size is less than or equal to 200 there will be no errors. So the execution statement we to modify like below:


What about the limit "Maximum number of Apex jobs added to the queue with System.enqueueJob=50"?

Per transaction, we can add up to 50 Queueable jobs to the Queue, please observe the below code snippet for understanding this limit.



Execute the below code snippet from Execute anonymous block:


tHiNk gooD and dO thE bEsT.........MANJU NATH 🌝

Comments