No comments yet

Batch Apex in Salesforce

A Batch Apex class allows you to define a single job that can be broken up into manageable chunks that will be processed separately. Batch Apex is a global class that implements the Database.Batchable interface. In this post we will learn about what is Batch Apex and when to use Batch Apex with example.

What is Batch Apex in Salesforce?

Batch class is used to process millions of records with in normal processing limits. With Batch Apex, we can process records asynchronously to stay within platform limits. If you have a lot of records to process, for example, data cleansing or archiving, Batch Apex is probably your best solution. In Batch Apex each transaction starts with a new set of governor limits, making it easier to ensure that your code stays within the governor execution limits.

When to use Batch Apex

Here is the real-time scenario to use Apex Batch job.

  1. If you want to send an email 90 days before the Contract expiration, we want to notify the User that the Contract is going to expire.
  2. Create a renewal opportunity base on contract end date.
  3. Batch Apex is also used to recalculate Apex Sharing for large data volume.

Batch Job Execution

Let understand how batch job execution happened and in which order all method execute.

1) Start method is identifies the scope (list of data to be processed) and automatically called at the beginning of the apex job. This method will collect record or objects on which the operation should be performed.

global Database.QueryLocator start(Database.BatchableContext BC){}

2) Execute Method processes a subset of the scoped records and performs operation which we want to perform on the records fetched from start method.

global void execute(Database.BatchableContext BC, list<sobject<) {}

3) Finish method executes after all batches are processed. This method use for any post job or wrap-up work like send confirmation email notifications.

global void finish(Database.BatchableContext BC) {}
Batch Apex in Salesforce
Batch Job Execution

Batch Apex Example In Salesforce

Let take one example for batch job in Salesforce. If you need to make a field update to every Account in your organization. If you have 10,001 Account records in your org, this is impossible without some way of breaking it up.

  1. So in the start() method, you define the query you’re going to use in this batch context: ‘select Id from Account’.
  2. Then the 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. 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 instantiated with the next group of 200 Accounts, with a brand new set of governor limits.
  3. Finally the finish() method wraps up any loose ends as necessary, like sending a status email.
Batch Apex in Salesforce and UNDERSTANDING BATCH APEX

Sample Batch Job

here is sample batch job.

global class AccountUpdateBatchJob 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 by Batch job';
        update scope;
    global void finish(Database.BatchableContext BC) {

How to execute a Batch job?

You can execute a batch job with DataBase.executeBatch(obj,size) method or we can schedule a batch job with scheduler class. Let see how to execute a batch job

AccountUpdateBatchJob obj = new AccountUpdateBatchJob();
Batch Apex in Salesforce

Scheduler Class For Batch Apex

Schedulable Class is a global class that implements the Schedulable interface. That includes one execute method. Here is example of scheduler class

global class AccountUpdateBatchJobscheduled implements Schedulable {
    global void execute(SchedulableContext sc) {
        AccountUpdateBatchJob b = new AccountUpdateBatchJob(); 

How to Schedule scheduler class

There are two option we have schedule the scheduler classes.
1) By System Scheduler.
2) By Developer console

System Scheduler

Step 1) Click on Setup->Apex class. Then search Schedule Apex button.

Step 2) Select the scheduler class and set Time like below screen shot.

By Developer console

Execute below code from developer console.

AccountUpdateBatchJobscheduled m = new AccountUpdateBatchJobscheduled();
String sch = '20 30 8 10 2 ?';
String jobID = system.schedule('Merge Job', sch, m);

Test Class for Batch Job

How to write test class for Batch Job.

public class AccountUpdateBatchJobTest {
    static testMethod void testMethod1() {
        List<Account> lstAccount= new List<Account>();
        for(Integer i=0 ;i <200;i++) {
            Account acc = new Account();
            acc.Name ='Name'+i;
        insert lstAccount;
            AccountUpdateBatchJob obj = new AccountUpdateBatchJob();

Limits in Batch Apex

  1. Up to five queued or active batch jobs are allowed for Apex
  2. Cursor limits for different features are tracked separately. For example, you can have 50 Apex query cursors, 50 batch cursors, and 50 Visualforce cursors open at the same time.
  3. 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
  4. If the start method returns a QueryLocator, the optional scope parameter of Database.executeBatch can have a maximum value of 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 the start method returns an iterable, the scope parameter value has no upper limit; however, if you use a very high number, you may run into other limits.
  5. If no size is specified with the optional scope parameter of Database.executeBatch, Salesforce chunks the records returned by the start method into batches of 200, and then passes each batch to the execute method.Apex governor limits are reset for each execution of execute.
  6. The start, execute, and finish methods can implement up to 10 callouts each
  7. The maximum number of batch executions is 250,000 per 24 hours
  8. 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


In this post we learn about what is Batch Apex in Salesforce and when we should use Batch Apex. I hope this helped you to learn how batch class is used to process millions of records with in normal processing limits.

Post a comment