I've been looking for similar questions, but none of them applies to my scenario, so I'd be grateful if you can explain me why my logic is failing, and what can I do in order to fix it.
-
I want to run every month a logic on Account records (>50k) : BATCHS
-
This logic will create X events on each account : Event Trigger
-
For new Events, I need to sync the data with other system : @future method
So, since Batchs cannot call another future methods, I decided to implement the @future logic inside a Queueable class.
Here is a snippet:
Batch
global class BATCH_GeneradorEventos implements Database.Batchable<sObject>
{
...
global void execute(Database.BatchableContext BC, List<sObject> scope)
{
...
insert evs;
}
...
}
Event trigger
ID jobID = System.enqueueJob(new EventQueueableJob(Trigger.newMap.keySet()));
Queuable class
public class EventQueueableJob implements Queueable, Database.AllowsCallouts
{
...
public void execute(QueueableContext context)
{
// future methods and logic
}
}
The error that I'm getting is:
"Too many queueable jobs added to the queue: 2"
and it's giving me for every SerialBatch.
Is it because I'm doing an enqueueJob for every iteration of the Batch? If so, how can I fix/remodel it?
Thank you in advance!
Best Answer
You have two things going on here:
So if you update 201 records, you will have one
Queueable
kicked off with 200 records, and another kicked off with just one record. As soon as you execute a second job, you're going to error out. The simple fix is to keep your batch size low enough that you knowevs
will contain fewer than 200 records. A more robust fix is to add some logic to check if you should execute synchronously or asynhronously, and only useQueueable
in the latter case.