Search

Friday 18 November 2011

Serialize Batch Apex

In Force.com you cannot call a batch Apex class from another batch Apex class because batch Apex is a future call. However, you can use Database.Stateful and the finish() method to mimic serialization of batch processes.

After batch 1 is complete in the finish() method this calls startNewBatch() in GeneralUtils which fires the newbacth batch class


However, running this you will see an error
Database.executeBatch cannot be called from a batch or future method.


global class batch l implements Database.Batchable<sObject>, Database.Stateful{

global Database.QueryLocator start(Database.BatchableContext BC){
return Database.getQueryLocator(query);
}

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

}

global void finish(Database.BatchableContext BC){

     GeneralUtils.startNewBatch();
}

}

public class GeneralUtils{

 public static void startNewBatch(){
    newbacth batchable = new newbacth();
    Id
newbacthID = Database.executeBatch(batchable);
}