Batch Apex in Salesforce

A developer can now employ batch Apex to build complex, long-running processes that run on thousands of records on the Force.com platform. Batch Apex operates over small batches of records, covering your entire record set and breaking the processing down to manageable chunks. For example, a developer 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 a developer could build a data cleansing operation that goes through all Accounts and Opportunities on a nightly basis and updates them if necessary, based on custom criteria.

Batch Apex is exposed as an interface that must be implemented by the developer. Batch jobs can be programmatically invoked at runtime using Apex.

To use batch Apex, you must write an Apex class that implements the Salesforce-provided interface Database.Batchable, and then invoke the class programmatically.

To monitor or stop the execution of the batch Apex job, go to Setup --> Monitoring --> Apex Jobs. For more information, see “Monitoring the Apex Job Queue” in the Salesforce online help.

The Database.Batchable interface contains three methods that must be implemented:

start method

global (Database.QueryLocator | Iterable<sObject>) start(Database.BatchableContext bc) {}
The start method is called at the beginning of a batch Apex job. Use the start method to collect the records or objects to be passed to the interface method execute. This method returns either a Database.QueryLocator object or an iterable that contains the records or objects being passed into the job.

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:

1. A reference to the Database.BatchableContext object.

2. 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.
Batch Apex Governor Limits

Keep in mind the following governor limits for batch Apex:

  • Up to five queued or active batch jobs are allowed for Apex.
  • A user can have up to five query cursors open at a time. For example, if five cursors are open and a client application still logged in as the same user attempts to open a new one, the oldest of the five cursors is released.
  • Cursor limits for different Force.com features are tracked separately. For example, you can have five Apex query cursors, five batch cursors, and five 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.
  • The maximum value for the optional scope parameter is 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 no size is specified with the optional scope parameter, Salesforce chunks the records returned by the QueryLocator 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 only one callout in each method.
  • Batch executions are limited to one callout per 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.

Step 1: Write an apex class for Batch Apex.

Sample code:

global class AccountUpdate implements Database.batchable<sObject>
{

    String query,field,value;
   
    global AccountUpdate(String f, String v)
    {
        field = f;
        value = v;
        query = 'Select ' + field + ' FROM Account';
    }

    global Database.QueryLocator start(Database.BatchableContext BC)
    {
        return Database.getQueryLocator(query);
    }
   
    global void execute(Database.BatchableContext BC, List<sObject> scope)
    {
         for(sobject s : scope)
         {
             s.put(Field,Value);
         }
         update scope;
    }
   
    global void finish(Database.BatchableContext BC)
    {
    }
   
}

The above class is used to update Description field with some value.

Step 2: Go to Setup à Developer Console.


Step 3: Execute the Batch Apex.



Step 4: Monitor the Apex jobs.

To monitor the Apex jobs, go to Setup --> Monitoring --> Apex Jobs.



Cheers!!!

13 comments:

  1. How can I run this code from a VF page by clicking a button.Thank you in advance!

    ReplyDelete
    Replies
    1. Write a method in the controller and call it in the VF page using a command button. Inside the method use the below code

      BatchClass obj = BatchClass();
      Database.executeBatch(obj);

      here BatchClass is the name of the batch class.

      Cheers!

      Delete
  2. Why finish method is compulsory even if we don't want to send an E-mail ?

    ReplyDelete
    Replies
    1. Since it is implementing the interface class, where it has been made compulsory.

      Cheers!!!

      Delete
  3. We need to execute 4 batch jobs in order, how to do that.

    ReplyDelete
    Replies
    1. In order to execute the Batch classes in order, call the second batch class in finish of first bacth.

      Cheers!!!

      Delete
  4. How should i update multiple objects in single batch job? please give an example..

    ReplyDelete
  5. If there are 1 lakh records in Batch how many times the start and execute method will execute

    ReplyDelete
    Replies
    1. You can query upto 50 Million (5 Crore) records at once in start() method using Database.getQueryLocator() method. start() and finish() methods run only once no matter what, execute() method runs multiple times. In your case if the return type of start() method in Database.QueryLocator then start() method can return upto 2000 records at once to execute() method which means execute() method can run 50 times (100,000/ 2,000).

      Delete
  6. I think , if there are 1 lakh records in batch, Start method will execute only once and Execute method will run 500 times.

    ReplyDelete
  7. Difference between QueryLocator and an Iterator?

    ReplyDelete
    Replies
    1. Check this - http://www.infallibletechie.com/2013/04/what-is-difference-between.html

      Delete