Thursday, 10 January 2013

How to write Batch Class in Apex


batchApexIn order for us to write batch classes in apex, let us 1st understand what is batch class , when and where it should be used? This is an extensive blog going into details.
Main sections of this post are
  1. What is batch Apex
  2. When to use batch apex
  3. Advantages of using batch apex
  4. Batch Apex Governor limits
  5. Sample Code

What is Batch Apex ?

Batch as the name suggests, is used when a large data (bulk) volume is involved and it has to be redundantly processed using a particular logic.
The Batch apex, can be used to conveniently perform time to time task and some real complex job ranging from data cleansing, archiving the data to the other quality improvements. 

When to use Batch Apex?

The typical use of batch apex is when you want to do a bulk job, but if you do it in a regular apex you’re bound to hit the governor limits. Batch Classes process the set of records you pass to it in batches of maximum 200 per batch. To learn more about the governor limits go here , or you can check out the presentation at slideshare below
Advantages of using Batch Apex?

  • Higher Governor Limits
  • Can be used to process in batches
  • Can be scheduled to run at different time. (read more)
  • Work around to other governor limits e.g. Send More than 10 E-mails blog by Ankit Arora

  • here is the governor limit difference in using batch
    Normal Context
    Batch Context
    SOQL queries 100 SOQL per cycle 200 SOQL per cycle
    records retrieved by SOQL queries 50,000 50,000,000 (getQueryLocator)
    executed code statements 200,000 1,000,000 (Winter '14)
    Heap size 6 MB 12 MB

    Batch Apex Governor Limits

    These are the governor Limits you need to keep in mind when dealing with Batch Apex
    • Up to five queued or active batch jobs are allowed for Apex.
    • A user can have up to 50 query cursors open at a time. For example, if 50 cursors are open and a client application still logged in as the same user attempts to open a new one, the oldest of the 50 cursors is released. Note that this limit is different for the batch Apex start method, which can have up to five query cursors open at a time per user. The other batch Apex methods have the higher limit of 50 cursors. Cursor limits for different features are tracked separately. For example, you can have 50 Apex query cursors, 50 batch cursors, and 50 Visualforce cursors open at the same time.
    • A maximum of 50 million records can be returned in the Database.QueryLocator object. If more than 50 million records are returned, the batch job is immediately terminated and marked as Failed.
    • If the start method returns a QueryLocator, the optional scope parameter of Database.executeBatch can have a maximum value of 2,000. If set to a higher value, Salesforce chunks the records returned by the QueryLocator into smaller batches of up to 2,000 records. If the start method returns an iterable, the scope parameter value has no upper limit; however, if you use a very high number, you may run into other limits.
    • If no size is specified with the optional scope parameter of Database.executeBatch, Salesforce chunks the records returned by the start method into batches of 200, and then passes each batch to the execute method. Apex governor limits are reset for each execution of execute.
    • The start, execute, and finish methods can implement up to 10 callouts each.
    • Batch executions are limited to 10 callouts per method execution.
    • The maximum number of batch executions is 250,000 per 24 hours.
    • Only one batch Apex job's start method can run at a time in an organization. Batch jobs that haven’t started yet remain in the queue until they're started. Note that this limit doesn't cause any batch job to fail and execute methods of batch Apex jobs still run in parallel if more than one job is running.

    Sample Code

    Batch Class :
       global class ExampleBatchClass implements Database.Batchable<sObject>{
            global ExampleBatchClass(){
                       // Batch Constructor
            // Start Method
            global Database.QueryLocator start(Database.BatchableContext BC){
             return Database.getQueryLocator(query);
          // Execute Logic
           global void execute(Database.BatchableContext BC, List<sObject>scope){
                  // Logic to be Executed batch wise      
           global void finish(Database.BatchableContext BC){
                // Logic to be Executed at finish

    Call the Batch Class :

              ExampleBatchClass b = new ExampleBatchClass(); 
              //Parameters of ExecuteBatch(context,BatchSize)
    Note : if batch size is not mentioned it is 200 by default.

    That’s about it for this post, if you still want a deep dive into Batch Classes I suggest you read this

    Do let me know your thoughts Happy Coding !