Using Stateful Batch Apex

Batch Apex is stateless by default. That means for each execution of your execute method, you receive a fresh copy of your object. All fields of the class are initialized, static and instance. If your batch process needs information that is shared across transactions, one approach is to make the Batch Apex class itself stateful by implementing the Stateful interface. This instructs Force.com to preserve the values of your static and instance variables between transactions.


Ex:

global class MyBatch implements Database.Batchable<sObject>,Database.statefull{
   private static Integer queryCount = 0;
   global MyBatch(){
        
   }

   global Database.QueryLocator start(Database.BatchableContext BC){
      return Database.getQueryLocator('Your Query');
   }

   global void execute(Database.BatchableContext BC, 
                       List<Sobject> scope){
   //should be the last line 
    queryCount = queryCount ++
     
   }

   global void finish(Database.BatchableContext BC){
        
   //use queryCount  here
   }

}

Comments

Popular posts from this blog

Approval Process

Spring Batch 2.0 -Basic Concepts

Sending Mass Emails From Salesforce