0

Got a triggerhandler class that creates a collection of things and passes them over to Batch Apex for processing. That batch handler, in it's finish method, then hands off to another batch class. All good, this is just batch chaining.

EXCEPT some managed package is also using batches and somewhere in what it is doing, it fires my trigger and goes down the path I just described, but not neatly, so we get

Database.executeBatch cannot be called from a batch start, batch execute, or future method

What can I do here, given it's a managed package so I can't refactor it?

2
  • 1
    Take a look at the quote provided by sfdcfox in his answer to another question then have a look at my suggested approach in my answer to that question. Basically decouple your batch from your trigger since it is a fragile design and will break (you just found one of many things that do this).
    – Phil W
    Oct 8, 2021 at 11:43
  • 1
    A rich vein of material there, for sure. Once I get past the shock of "I've got to rewrite this across 3 client projects", I'll have a crack at refactoring to that pattern
    – Rob Cowell
    Oct 8, 2021 at 13:42

1 Answer 1

1

Not a correct solution solution as mentioned by @phil-w in comments.

One solution is to make your trigger fire a qeueuable class where you can write code to chain your batch. Like

trigger triggerClass on Lead(before insert) {
if(Trigger.isInsert){
    System.enqueueJob(new QueueExample(Trigger.New));
}
}

public class QueueExample implements Queueable {
    private List<CustomOBject__c> objs;
              
    public QueueExample(List<CustomObject> recs) {
          this.objs = recs;
    }
              
    public void execute(QueueableContext queCont) {
          Database.executeBatch(new BatchClass());
    }

}
1
  • 3
    Starting queueables from a trigger is also going to cause issues in bulk update contexts. In a synchronous context you can start up to 50 queueables (across the whole transaction) but in async you can only start 1. If you have async processing that causes more than 1 chunk to be sent to your trigger you're going to violate these constraints.
    – Phil W
    Oct 8, 2021 at 11:44

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .