Asynchronous Apex : Batch Apex

Asynchronous Apex : Batch Apex

Batch Apex :

Batch Apex has the capability to execute substantial jobs, allowing for the processing of thousands or even millions of records. This processing takes place asynchronously, as the system divides the extensive record set into multiple batches, which are subsequently executed.

For every batch, the same logic is applied.

Whenever the batch class is triggered, the job is placed in the Apex Job Queue and executed as an independent transaction.

A fresh set of governor limits is initiated with each transaction.

In the event of a batch failing to process successfully, the failure does not cause a rollback of the other batches.

Syntax :

Must implement Database.Batchable interface and include the following methods:

  • start()
  • execute()
  • finish()


  1. Start() :

In the "start" method:

  • Gather records or objects intended for passing to the "execute" interface method.
  • The "start" method is invoked only once.
  • It returns a Database.QueryLocator object or an iterable containing records or objects.
  • When a QueryLocator object is used, governor limits are bypassed, permitting querying of up to 50 million records.
  • However, if an iterable is used, the governor limits are upheld.

2. Execute()

Within the "execute" method:

  • Business logic is defined and implemented.
  • Batches can be executed in any sequence, without a specific order.
  • The "execute" method is invoked multiple times during batch processing.
  • It accepts a reference to the Database.BatchableContext object, along with either a List<sObject> or a list of parameterized types.

3. Finish()

  • It is executed once all batches have been processed, whether they completed successfully or not.
  • This method allows you to perform any necessary cleanup tasks, final calculations, or post-processing operations.
  • It is called after the "execute" method has been executed for all batches and should be used to handle concluding actions.

Example :

Create Apex class

public class OppProcessor implements Database.Batchable<sObject>,Database.Stateful 


    public integer recordCount = 0;
    
    public Database.QueryLocator start(Database.BatchableContext bc)
    {
        return Database.getQueryLocator([SELECT Id,Name FROM Opportunity]);
    }
    
    public void execute(Database.BatchableContext bc,List<Opportunity> opps)
    {
        for(Opportunity op : opps)
        {
            op.LeadSource = 'Web';
        }
        
        update opps;
        recordCount = recordCount + opps.size();
    }
    
    public void finish(Database.BatchableContext bc)
    {
        System.debug('Total records processed '+ recordCount);
    }
}        

Anonymous window (ctrl + e) :

Id batchJobId = Database.executeBatch(new OppProcessor(),10);        

Test Class :

@isTest
public class OppProcessorTest {


    @isTest
    public static void testBatchClass()
    {
       List<Opportunity> oppList = new List<Opportunity>();
        
        for(integer i=0;i<200;i++)
        {
            oppList.add(new Opportunity(Name='test'+i,StageName='Prospecting',CloseDate=System.today()));
        }
        insert oppList;
        
        Test.startTest();
        OppProcessor oppProcess = new OppProcessor();
        Id batchId = Database.executeBatch(oppProcess);
        Test.stopTest();
        
        List<Opportunity> updatedOps = [SELECT Id FROM Opportunity WHERE LeadSource='Web'];
        
        System.assertEquals(200,updatedOps.size());
    }
    
}        


Result :

No alt text provided for this image







To view or add a comment, sign in

More articles by Swapnil Sable

Others also viewed

Explore content categories