Developing a Batch Apex Class

Although the class in Listing 9.1 performs no useful work, it leaves a trail of its activity in the debug log. This is helpful in understanding how Force.com handles your batch-enabled code. It also illustrates the basic elements of a Batch Apex class, listed next:

Image The class must implement the Database.Batchable interface. This is a parameterized interface, so you also need to provide a type name. Use SObject for batches with a QueryLocator scope, or any database object type for an Iterable scope.

Image The class must be global. This is a requirement of Batch Apex classes.

Listing 9.1 Sample Batch Apex Code


global class Listing9_1 implements Database.Batchable<SObject> {
  global Database.QueryLocator start(Database.BatchableContext context) {
    System.debug('start'),
    return Database.getQueryLocator(
      [SELECT Name FROM Project__c ORDER BY Name]);
  }
  global void execute(Database.BatchableContext context,
    List<SObject> scope) {
    System.debug('execute'),
    for(SObject rec : scope) {
      Project__c p = (Project__c)rec;
      System.debug('Project: ' + p.Name);
    }
  }
  global void finish(Database.BatchableContext context) {
    System.debug('finish'),
  }
}


Before actually running the code in the next subsection, review these implementation details:

Image The start method defines the scope by returning a QueryLocator object constructed from an in-line SOQL statement. The SOQL statement returns all Project records in ascending order by the Name field. The SOQL statement can use parameters (prefaced with a colon) like any in-line SOQL in Apex code. Relationship queries are acceptable, but aggregate queries are not allowed. You can also pass a SOQL string into the getQueryLocator method, which allows the scope of the batch to be specified with dynamic SOQL.

Image The execute method is called once per transaction with a unique group of up to 2,000 records from the scope. The records are provided in the scope argument.

Image The finish method is called when all transactions have completed processing, or the batch job has been interrupted for any reason.

Image The BatchableContext object argument in all three methods contains a method for obtaining the unique identifier of the current batch job, getJobID. This identifier can be used to look up additional information about the batch job in the standard database object AsyncApexJob. You can also pass this identifier to the System.abortJob method to stop processing of the batch job.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.139.103.206