7

Is it possible to keep a running count of all tasks by whoId in batch apex? I want to aggregate all tasks for a contact, but how do you prevent the count from resetting after each batch?

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

global final String query;
global integer hqCount;

global TaskRollupBatch() {
    query = 'select Id, WhoId, HQ_Activity__c, Call_Report__c from Task ALL ROWS';
    hqCount = 0;
}

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

global void execute(Database.BatchableContext BC, List<sObject> scope)
{               
    for (Task t : (List<Task>)scope) {
        if(t.HQ_Activity__c && t.WhoId == '003e000000EQ8fm') {
            hqCount = Integer.valueOf(t.get('Id')) + hqCount;
        }   
    }
    Contact c = [select HQ_Total__c from Contact where Id = '003e000000EQ8fm'];
    c.HQ_Total__c = hqCount;
    update c;
}

global void finish(Database.BatchableContext BC) {

}
}

Thanks for any help.

8

To do this you would want to implement Database.Stateful. There's a great example of how to do this in the documentation

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){

   }
}

Here the link : http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_batch_interface.htm

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.