How To Create Batch Apex In Salesforce

How To Create Batch Apex In Salesforce

By admin December 17, 2013
Blog, Salesforce Development 0

Another question has been asked to our expert Salesforce developers and we thought best to share it on our blog. A batch class allows you to define a single job that can be broken up into manageable chunks that will be processed separately.

Let’s use a simple example, lets say that if you need to make a field update to every Account in your organization, how would you do that? If you have thousands of Account records in your organization it will be very difficult to manage this. It will be almost impossible without breaking it up somehow. So in the start () method, you define the query you’re going to use in this batch context: ‘select Id from Account’. Then, execute () method runs, but only receives a relatively short list of records (default 200). Within the execute (), everything runs in its own transactional context, which means almost all of the governor limits only apply to that block within Salesforce. Thus each time execute () is run, you are allowed 150 queries and 50,000 DML rows and so on. When that execute () is complete, a new one is initiated with the next group of 200 Accounts, with a brand new set of governor limits. Finally, finish () method wraps up any loose ends as necessary, like sending a status email.

Follow these simple steps within Salesfroce for creating Batch Apex in your Class:


Step 1 :


Go To Setup → Develop → Apex Classes


Click “New” Button for creating new Apex Class


Visualforce Pages


Step 2 : Paste this code in Apex class editor within Salesforce


global class BulkUpdateAccount 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){list<account> acclist = new list<account>();for(Account a : scope){a.status__c= ‘Inactive’;acclist.add(a);


update acclist;


global void finish(Database.BatchableContext BC)





Save” this code.


Step 3 : Execute this batch Apex class in Salesforce developer Console


Paste this code in Salesforce developer console:


BulkUpdateAccount   bulkupdate=  new   BulkUpdateAccount();database.executeBatch(bulkupdate);


And execute this code.


Create Batch Apex


Step 4 :

Now you can check in your account object within Salesforce

We hope this simple walk through has helped anyone having trouble within Salesforce. As always please feel free to ask any question to our expert Salesforce developers as we would be more than happy to help.

Related Posts

Popular post