Thursday, 30 August 2012

Apex Batch Processing


Using batch Apex classes, you can process records in batches asynchronously. If you have a large number of records to process, for example, for data cleansing or archiving, batch Apex is your solution. Each invocation of a batch class results in a job being placed on the Apex job queue for execution.
The execution logic of the batch class is called once for each batch of records. The default batch size is 200 records. You can also specify a custom batch size. Furthermore, each batch execution is considered a discrete transaction. With each new batch of records, a new set of governor limits is in effect. In this way, it’s easier to ensure that your code stays within the governor execution limits. Another benefit of discrete batch transactions is to allow for partial processing of a batch of records in case one batch fails to process successfully, all other batch transactions aren’t affected and aren’t rolled back if they were processed successfully.

Batch Apex Syntax

To write a batch Apex class, your class must implement the Database.Batchable interface. Your class declaration must include the implements keyword followed by Database.Batchable<sObject>. Here is an example:
global class CleanUpRecords implements Database.Batchable<sObject> {
You must also implement three methods:
  • start method
    global (Database.QueryLocator | Iterable<sObject>) start(Database.BatchableContext bc) {}
    The start method is called at the beginning of a batch Apex job. It collects the records or objects to be passed to the interface methodexecute.
  • execute method:
    global void execute(Database.BatchableContext BC, list<P>){}
    The execute method is called for each batch of records passed to the method. Use this method to do all required processing for each chunk of data.
    This method takes the following:
    • A reference to the Database.BatchableContext object.
    • A list of sObjects, such as List<sObject>, or a list of parameterized types. If you are using a Database.QueryLocator, the returned list should be used.
    Batches of records are not guaranteed to execute in the order they are received from the start method.
  • finish method
    global void finish(Database.BatchableContext BC){}
    The finish method is called after all batches are processed. Use this method to send confirmation emails or execute post-processing operations.

Invoking a Batch Class

To invoke a batch class, instantiate it first and then call Database.executeBatch with the instance of your batch class:
BatchClass myBatchObject = new BatchClass();
Database.executeBatch(myBatchObject);
In the next steps of this tutorial, you’ll learn how to create a batch class, test it, and invoke a batch job.

No comments:

Post a Comment