Saturday, 21 September 2013

Callouts in Batch Apex,State in Batch Apex

Using Callouts in Batch Apex
To use a callout in batch Apex, you must specify Database.AllowsCallouts in the class definition. For example:

global class SearchAndReplace implements Database.Batchable<sObject>, 
   Database.AllowsCallouts{
              //Business logic you want by implementing Batchable interface methods
}
Callouts include HTTP requests as well as methods defined with the webService keyword.

Using State in Batch Apex
Each execution of a batch Apex job is considered a discrete transaction. For example, a batch Apex job that contains 1,000 records and is executed without the optional scope parameter is considered five transactions of 200 records each.
If you specify Database.Stateful in the class definition, you can maintain state across these transactions. When using Database.Stateful, only instance member variables retain their values between transactions. Static member variables don’t and are reset between transactions. Maintaining state is useful for counting or summarizing records as they're processed. For example, suppose your job processed opportunity records. You could define a method in execute to aggregate totals of the opportunity amounts as they were processed.
If you don't specify Database.Stateful, all static and instance member variables are set back to their original values.
The following example summarizes a custom field total__c as the records are processed:
global class SummarizeAccountTotal implements 
    Database.Batchable<sObject>, Database.Stateful{

   global final String Query;
   global integer Summary;
  
   global SummarizeAccountTotal(String q){Query=q;
     Summary = 0;
   }

   global Database.QueryLocator start(Database.BatchableContext BC){
      return Database.getQueryLocator(query);
   }
   
   global void execute(
                Database.BatchableContext BC, 
                List<sObject> scope){
      for(sObject s : scope){
         Summary = Integer.valueOf(s.get('total__c'))+Summary;
      }
   }

global void finish(Database.BatchableContext BC){
   }
}

1 comment:

  1. can u write test class for this it will be help for beginners

    ReplyDelete