Play Games

Search This Blog

Wednesday, August 27, 2014

Batch Apex in Salesforce

Batch Apex in Salesforce

Batch Jobs : What is the need ?

       As you all might know about the salesforce governor limits on its data. When you want to fetch thousands of records or fire DML on thousands of rows on objects it is very complex in salesforce and it does not allow you to operate on more than certain number of records which satisfies the Governor limits.
But for medium to large enterprises, it is essential to manage thousands of records every day. Adding/editing/deleting them when needed.
There is a  powerful concept called Batch Apex. Batch Apex allows you to handle more number of records and manipulate them by using a specific syntax.
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.
Batch job are made to perform common UPSERT operation on a scheduled basis. 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.
Advantages:
  • A large number of records can be processed. Even batch size is changeable.
  • Result of one batch cannot affect other batch.It means every batch is descrete.
  • 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.
How to Implement:
Develop Apex class implementing 'Batchable' Interface. This interface has three operation defined to it. In order to implement batch processing, first we need to create an Apex class that implements Database.Batchable<sObject> interface.
This interface demands for three methods to be implemented:
Start - Use this to basically collect the records and then pass on to execute method
Execute-  Use this to process the records.
Finish - Called once, when processing get finished and can be used for operations like sending confirmation email
Lets jump to code, for better understanding.
Example:
Global class batchAccountUpdate implements Database.Batchable<sObject> {
   Global Database.QueryLocator start(Database.BatchableContext BC) {
       String query = 'SELECT Id,Name FROM Account';
       return Database.getQueryLocator(query);
   }   
   Global void execute(Database.BatchableContext BC, List<Account> scope) {
        for(Account a : scope) {
a.Name = a.Name + 'Updated';            
        }
        update scope;
   }   
   Global void finish(Database.BatchableContext BC) {
AsyncApexJob a = [SELECT Id, Status, NumberOfErrors,
JobItemsProcessed,TotalJobItems, CreatedBy.Email
FROM AsyncApexJob WHERE Id =:BC.getJobId()];
String UserEmail = 'Any EMAIL';
Messaging.SingleEmailMessage mail = new      Messaging.SingleEmailMessage();
mail.setToAddresses(new String[] {UserEmail});
mail.setReplyTo('ANY EMAIL');
mail.setSenderDisplayName('Batch Processing');
mail.setSubject('Batch Process Completed');
mail.setPlainTextBody('Batch Process has completed');
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
   }
}

How to run Batch Process:

In order to run batch process, you need to use
Database.executeBatch() method.
Open the developer console and then write a small snippet of apex code as shown below
batchAccountUpdate batchJob = new batchAccountUpdate();
Database.executeBatch(batchJob);
Scheduling Batch Process:
We can also schedule batch apex. In order to schedule batch class,we need to write schedulable batch class.
Example:
Global class batchAccountUpdateSchedular implements Schedule
{
Global void execute(SchedulableContext sc)
{
          batchAccountUpdate b= new batchAccountUpdate();
  Database.executebatch(b);
}
}
Now you can schedule this apex class by using Schedule Apex in Salesforce.

No comments:

Post a Comment