function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
TarentTarent 

How to use Batch Apex in Salesforce

Batch Apex in salesforce

Navatar_DbSupNavatar_DbSup

Hi,

Among the many new goodies in summer ’09 release is a powerful new feature to do batch processing on your database records.  Tasks that require processing of large data volumes without any active human intervention can take advantage of this feature.  As an example, consider the task of validating addresses in your contacts when you can potentially have millions of contact records.  A batch job would be ideal for this scenario since you can start the batch job, continue to work or even log off while the job continues to execute.

 

To use this functionality, you need to implement the Database.Batchable interface.  You can find an example of the usage in the Apex Code Developer’s Guide.  The Database.Batchable interface has three methods that you would need to implement as shown below

global class MyBatchTest implements Database.Batchable

global Database.QueryLocator start() { ... }    global void executeBatch( SObject[] batch) { ... }  global void finish() { ... }}

The start() method determines the set of records that will be processed by the executeBatch method. You would need to construct a SOQL query and return a QueryLocator object. For example,

return Database.getQueryLocator( 'SELECT Name, MailingAddress FROM Contact' )

would return all contact records for processing. You can ofcourse, make the query as selective as you wish with additional filter criteria. There is a limit of five fifty million records which can be returned by the QueryLocator object.

To start a batch job, you create and instance of this class and call the executeBatch method.

MyBatchTest b = new MyBatchTest( ... ) ;    ID myBatchJobID = Database.executeBatch(b) ;

When you call executeBatch on your instance, the system enqueues the job for processing and returns an ID. When the system is ready to execute the job, it calls the start method and then calls the executeBatch method for chunks of 200 records. So if the QueryLocator returned back 1000 records, the executeBatch method will be called five times. The batch job is run using the permission of the user that enqueued the job. The finish method is called after all records have been processed and can be used to perform any post-processing tasks like sending out e-mails etc. The ID returned by the Database.executeBatch method can be used to monitor the status of the job programmatically by querying the AsynchApexJob queue. You can also monitor the job under Setup->Monitoring->Apex Jobs.

The documentation has additional details on usage, governor limits and a few best practices. A common question that comes up is the ability to schedule jobs at a certain time or with some periodicity (for example run a job every day at midnight). This feature is not (yet) available. Also, the batch Apex feature is still in preview mode and has to be explicitly provisioned for your org. If you need this feature, please contact support with a short description of your use case.

Finally, I would encourage you to sign up for the Summer ’09 preview, it has a lot of other cool new features!

 

Use:-

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).

 

view plainprint?

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.

 

Did this answer your question? If not, let me know what didn't work, or if so, please mark it solved. 

saranya srinivasansaranya srinivasan

The requirement is that email should be sent after each batch completes..Can u help me with that?

Gopinath.AGopinath.A

Hi friends,

 

                iam new to work with Batch Apex .so, i want to know how to create batch apex and how to call in triggers and           vfpages.Please provide me some sample examples.

 

 

Thanks,

Gopinath.A 

 

 

gautam_singhgautam_singh
global class expireNotify implements Database.Batchable<sObject>
{
    global Database.QueryLocator start(Database.BatchableContext bc)
    {
        Date d = Date.today();
        String soql = 'SELECT Expiry_Date__c, Name, Email_Address__c FROM Member__c WHERE Expiry_Date__c =: d';
        return Database.getQueryLocator(soql);
    }
   
    global void execute(Database.BatchableContext bc, List<Member__c> recs)
    {
        List<Messaging.SingleEmailMessage> mailList = new List<Messaging.SingleEmailMessage>();
        for(Member__c m : recs)
        {
            List<String> toAddresses = new List<String>();           
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
            toAddresses.add(m.Email_Address__c);
            mail.setToAddresses(toAddresses);
            mail.setSubject('Welcome to Sweet 16 Siebel Batch');
            String messageBody = '<html><body>Hi ' + m.Name + ',<br>Your account Expires today. <br>Kindly contact your administrator.<br><br><b>Regards,</b><br>Magulan D</body></html>';
            mail.setHtmlBody(messageBody); 
            mailList.add(mail);          
        } 
        Messaging.sendEmail(mailList);
    }
   
    global void finish(Database.BatchableContext bc)
    {
    }
}

 If in case you need to send mail via Batch Apex .


Important :

Hit kudo's if you get useful information from this post.