Running a Batch Job in Apex with mass records

March 5, 2012 § Leave a comment

A scenario comes when you need to process mass records either updating or inserting or deleting. We can make use of Batch Apex to process all the records at once.

Excerpts from the Force.com Winter ’10 Release :
Batch Apex gives you the ability to operate over large amounts of data by chunking the job into smaller parts, thereby keeping within the governor limits. Using batch Apex, you can build complex, long-running processes on the Force.com platform. For example, you could build an archiving solution that runs on a nightly basis, looking for records past a certain date and adding them to an archive. Or you could build a data cleansing operation that goes through all Accounts and Opportunities on a nightly basis and reassigns them if necessary, based on custom criteria.

In order to develop our Batch Apex, we need to create a new Apex class which extends “Database.Batchable” interface.

This interface will have three methods to be implemented:

  • start
  • execute
  • finish

“start” method is called at the beginning of a batch Apex job. Use this method to collect the records (of objects) to be passed to the “execute” method for processing. The Apex engine, automatically breaks the massive numbers of records you selected into smaller batches and repeatedly calls the “execute” method until all records are processed.

The “finish” method is called once all the batches are processed. You can use this method to carry out any post-processing operation such as sending out an email confirmation on the status of the batch operation.

Let’s take a closer look at each of these methods:
1. Start Method

global Database.QueryLocator start(Database.BatchableContext BC) {
      //passing the query string to the Database object.      
      return Database.getQueryLocator(query);
}

2. Execute method

 global void execute(Database.BatchableContext BC, List<sObject> scope){
    List<Account> accns = new List<Account>();

   for(sObject s : scope){Account a = (Account)s;
        if(a.OwnerId==fromUserId){
            a.OwnerId=toUserId;
            accns.add(a);
            }
        }
update accns;
}

3. Finish Method

global void finish(Database.BatchableContext BC){
  // Get the ID of the AsyncApexJob representing this batch job  
  // from Database.BatchableContext.    
  // Query the AsyncApexJob object to retrieve the current job's information.  

 AsyncApexJob a = [Select Id, Status, NumberOfErrors, JobItemsProcessed,
   TotalJobItems, CreatedBy.Email
   from AsyncApexJob where Id =:BC.getJobId()];

  // Send an email to the Apex job's submitter notifying of job completion.  
  Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
  String[] toAddresses = new String[] {a.CreatedBy.Email};
  mail.setToAddresses(toAddresses);
  mail.setSubject('Apex Sharing Recalculation ' + a.Status);
  mail.setPlainTextBody('The batch Apex job processed ' + a.TotalJobItems +
    ' batches with '+ a.NumberOfErrors + ' failures.');

  Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
}
}

Tagged: , , , ,

Leave a Comment

What’s this?

You are currently reading Running a Batch Job in Apex with mass records at Mandeep Deka.

meta