3

I'm aware that you can't call Database.executeBatch from the execute method of an already running Batchable.

But can Database.executeBatch be called from a Queueable running via System.enqueueJob? I'm asking because I'm looking to but an asynchronous layer on top of some code that is already using batchables.

(This Can Queueable solve "Future method cannot be called from a future or batch method"? confirms this works the opposite way round i.e. a Queueable can be called from a Batchable.)

PS

Interestingly, while Batchable -> Batchable isn't supported, Batchable -> Queueable -> Batchable is, so the Queueable insulates the pair of Batchables from that restriction.

5
  • Yes, you can I had tried that in the anonymous window. – rahul gawale Jan 21 at 13:59
  • 1
    Cool rahul, was just about to try it. Do post as an answer, especially if you can include the code – Keith C Jan 21 at 14:05
  • Sure, I need to find/write that again :P give me some time I will post. – rahul gawale Jan 21 at 14:11
  • I have added the answer below, thanks! – rahul gawale Jan 21 at 14:26
  • 1
    Cool thanks. I got the same results (both ways round) too. – Keith C Jan 21 at 14:38
4

Yes, you can do that.

This is my batch class

public class BatchableDemo implements Database.Batchable<sObject>{
    
    public Database.QueryLocator start(Database.BatchableContext bc) {
        return Database.getQueryLocator('Select id from Account');
    }
    public void execute(Database.BatchableContext bc, List<Account> records){
        // process each batch of records
        system.debug('In batch');
    }
    public void finish(Database.BatchableContext bc){
        // execute any post-processing operations
    }
    
}

This is the queueable class.

public class QueueableDemo implements Queueable {
    public static void execute(QueueableContext qc){
        Database.executeBatch(new BatchableDemo());
        System.debug('batch started');
    }
}

This is the code I ran from the anonymous window.

System.enqueueJob(new QueueableDemo());

Output

Queueable job log

enter image description here

Batch Job log

enter image description here

All logs list

enter image description here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.