Saturday, April 17, 2010

How to use Batch Apex in Salesforce


Batch Apex in salesforce 
As you all might know about the salesforce governer 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 Governer limits.
But for medium to large enterprises, it is essential to manage thousands of records every day. Adding/editing/deleting them when needed.
Salesforce has come up with a powerful concept called Batch Apex. Batch Apex allows you to handle more number of records and manipulate them by using a specific syntax.
We have to create an global apex class which extends Database.Batchable Interface because of which the salesforce compiler will know, this class incorporates batch jobs. Below is a sample class which is designed to delete all the records of Account object (Lets say your organization contains more than 50 thousand records and you want to mass delete all of them).

global class deleteAccounts implements Database.Batchable
{
global final String Query;
global deleteAccounts(String q)
{
Query=q;
}

global Database.QueryLocator start(Database.BatchableContext BC)
{
return Database.getQueryLocator(query);
}

global void execute(Database.BatchableContext BC,List scope)
{
List <Account> lstAccount = new list<Account>();
for(Sobject s : scope)
{
 Account a = (Account)s;
lstAccount.add(a);
}
Delete lstAccount;
}

global void finish(Database.BatchableContext BC)
{
                //Send an email to the User after your batch completes
                Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
String[] toAddresses = new String[] {‘sforce2009@gmail.com’};
mail.setToAddresses(toAddresses);
mail.setSubject('Apex Batch Job is done‘);
mail.setPlainTextBody('The batch Apex job processed ');
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
}
}


///////////////////This is how the batch class is called
id batchinstanceid = database.executeBatch(new deleteAccounts(‘select Id from Account’));

When you instantiate the global class and called it using database.executeBatch, the process gets started. As you have observed the deleteAccounts class accepts your query as a parameter in the constructor and sets it to the string variable called Query.
The start method of deleteAccount class which extends database.batchable interface sets the current query to execute using the Database.getQueryLocator method.
Then the result of the query can be captured in execute method. The scope list of SObjects returned as the result of your query.
When you are executing your batch with a query which returns thousands of records, the batch will be executed with 200 records each time that is salesforce divides the total number of records in to batches. Each batch contains 200 records by default (though this is configurable less than 200 by just introducing the number when you are calling the batch class like database.executebatch(new deleteAccounts(‘your query’), number here);).
After processing each batch, the governor limits are reset.
Once the whole batch of thousands records are done the Finish method gets called and an email will be sent to the specified person.


17 comments:

  1. Hi, when i save this class i got the error as

    Error: Compile Error: expecting a left angle bracket, found 'scope' at line 14 column 54

    How to solve these. Can you please help me out.

    Thanks,
    priya.

    ReplyDelete
  2. Hi,

    I want to display 1000 records from accounts.

    Is it possible to use that class to get all the records?

    I want to display all reords in visualforce. page.

    Can u help me out?

    ReplyDelete
  3. @Priya, it is a syntax error it seems, post your code if you need further assistance.

    ReplyDelete
  4. @bangar, to display records in a VF page, you don't need batch class. Custom Controller you can use.

    ReplyDelete
  5. Hi, Thanks.. Its working fine.

    Please help for, How to insert the records in to object through batch apex calss.

    Thanks,
    sravs.

    ReplyDelete
  6. how we can pick the value from xml file and put into salesforce instance

    ReplyDelete
  7. sir now iam learning stage in batch apex............so how to run the above batch program,i save this apex program in my developer instance with out errors but i dnt knw how to run and how to get output

    ReplyDelete
  8. Is it possible to fetch all accounts using Apex Batch and store it in database(db is on other external web-service).

    ReplyDelete
  9. hi srinivas,
    i want to send bulk mails more than 10 ,
    for that batch class is needed can u please tell me how to write batch apex for that i am new to batch apex it is bit touch to get understand for me.
    i am not able to post the code , it is showing that html is not allowed here

    ReplyDelete
  10. hi kishore,
    I am getting this error in
    Error: Compile Error: Type arguments must be supplied for parameterized type : Database.Batchable at line 1 column 40

    ReplyDelete
  11. Hi,

    Is there any possibility to display the message in vf page after completion of batch process.

    Thanks,
    Lakshmi

    ReplyDelete
  12. @anonymous
    i just wanted to know whether you wanna send the mails to same mail id or different?

    if it is single mail for different mail id's then you need to give all the mail id's.


    ReplyDelete
  13. global class deleteAccounts implements Database.Batchable
    {
    global final String Query;
    global deleteAccounts(String q)
    {
    Query=q;
    }

    global Database.QueryLocator start(Database.BatchableContext BC)
    {
    return Database.getQueryLocator(query);
    }

    global void execute(Database.BatchableContext BC, List scope)
    {
    List lstAccount = new list();
    for(Sobject s : scope)
    {
    Account a = (Account)s;
    lstAccount.add(a);
    }
    Delete lstAccount;
    }

    global void finish(Database.BatchableContext BC)
    {
    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
    String[] toAddresses = new String[] {'indrasens@consummatetechnologies.com'};
    mail.setToAddresses(toAddresses);
    mail.setSubject('Apex Batch Job is done');
    mail.setPlainTextBody('The batch Apex job processed ');
    Messaging.sendEmail(new Messaging.SingleEmailMessage[] {mail});
    }
    }

    ReplyDelete
  14. how to display batch apex in vf page ???

    ReplyDelete
  15. SingleEmail message is max1000 per 24 hours. Did it actually work after that?

    ReplyDelete
  16. Hi if i want to send an email that how many accounts are deleted and how many are not deleted,how it can be done plz explain

    ReplyDelete
  17. we have apex data loader right then why to go for BatchApex?

    ReplyDelete