Thursday, 30 August 2012

Adding a Batch Apex Class


Prerequisites:
  • Tutorial #2: Using the Developer Console
In this lesson, you’ll create a batch Apex class that implements the Database.Batchable interface. The batch class cleans up the records that are passed in by the start method.
  1. In the Developer Console, click the Repository tab.
  2. In the Setup Entity Type section, click Classes, and then click New.
  3. For the class name, enter CleanUpRecords and click OK.
  4. Delete the auto-generated code and add the following.
    global class CleanUpRecords implements 
       Database.Batchable<sObject> {
    
       global final String query;
       
       global CleanUpRecords(String q) {
           query = q;
       }
    
       global Database.QueryLocator start(Database.BatchableContext BC){
          return Database.getQueryLocator(query);
       }
       
       global void execute(
                    Database.BatchableContext BC, 
                    List<sObject> scope){
          delete scope;
          Database.emptyRecycleBin(scope);
       }
    
       global void finish(Database.BatchableContext BC){
           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('Record Clean Up Status: ' + a.Status);
           mail.setPlainTextBody
           ('The batch Apex job processed ' + a.TotalJobItems +
           ' batches with '+ a.NumberOfErrors + ' failures.');
           Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
       }
    }
  5. Click Save.

Tell Me More...

  • The records provided to this batch class are based on a query that is specified by the query variable. This query variable is set in the constructor of this class.
  • For each batch of records, the three methods in this class are executed starting with the start method, then the execute method, then the finish method, in this order.
  • The start provides the batch of records that the execute method will process. It returns the list of records to be processed by callingDatabase.getQueryLocator(query);. The maximum number of records that can be returned in theDatabase.QueryLocator object is 50 million.
  • The list of batch records to process is passed in the second parameter of the execute method. The execute method simply deletes the records with the delete DML statement. Since deleted records stay in the Recycle Bin for 15 days, the method also empties the Recycle Bin to delete these records permanently.
  • When a batch Apex job is invoked, a new record is added in the AsyncApexJob table that has information about the batch job, such as its status, the number of batches processed, and the total number of batches to be processed. The finish method sends an email to the job’s submitter to confirm the job completion. It performs a query on the AsyncApexJob object to get the status of the job, the submitter’s email address, and other information. It then creates a new email message and sends it using theMessaging.SingleEmailMessage methods.
In the next , you’ll add a test method that invokes this batch class.

No comments:

Post a Comment