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.

Leave a Reply