+ Start a Discussion
James L.James L. 

Can batch.execute be called directly?

The regular approach to execute batch job is use " Database.executeBatch", can batch.execute be called directly? if so, any special attention needed? say I have a batch class like

 

global without sharing class BatchA implements Database.Batchable <sObject>{
    global Database.QueryLocator start(Database.BatchableContext BC){
      return Database.getQueryLocator([select ID from Account]);
   }


   global void execute(Database.BatchableContext BC, List<sObject> scope){
      ...
   }

   global void finish(Database.BatchableContext BC) {

   }

}

 

Is it safe to call like

 

BatchA myBatch = new BatchA();

myBatch.execute(NULL, [select id from account limit 100]);

Best Answer chosen by Admin (Salesforce Developers) 
Sean TanSean Tan

It shouldn't cause any problems to call it directly. It's simply a class that implements the batchable interface.

All Answers

Sean TanSean Tan

It shouldn't cause any problems to call it directly. It's simply a class that implements the batchable interface.

This was selected as the best answer
sfdcfoxsfdcfox
The preferred method of testing a batch class is through the database.executebatch static function. This will test "start", "execute", and "finish" for you all at once. However, as Sean pointed out, these methods are perfectly ordinary methods, and can be invoked directly without going through the standard interface. The only caveat is that if your code uses the Database.BatchableContext parameter, you can't construct this data type (at least, not as far as I'm aware), and so your batch class would have to check and see if BC is null or not before accessing it.
James L.James L.
Thanks guys. This helps. Actually I'm not calling it for testing, just calling it for regular feature developmennt