Posts

Showing posts with the label Saleforce batch class

Salesforce Hacks: Call a batch class from execute method of another batch class

If we talk about chaining of batch classes, Salesforce provides a way to chain batch classes by calling a batch class from finish method of another batch class. For example, if you have a requirement to call Batch2 from Batch1, then in the finish method of Batch1, you can call Batch 2 as shown below: // Finish method of Batch1 global void finish(Database.BatchableContext BC) {     Database.executeBatch(new Batch2(), 1); } Recently, I had a requirement in which I need to call Batch2 from execute method of Batch1 as shown below: // Execute method of Batch1 global void execute(Database.BatchableContext BC, List<Account> scope) {         Database.executeBatch(new Batch2(), 1); } With this code, when Batch1 runs, Salesforce will throw you below exception: System.AsyncException: Database.executeBatch cannot be called from a batch start, batch execute, or future method. To bypass this error, we need to create a Queueable class and then enqueue this Queueable class from the execute met