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:
In the "start" method:
2. Execute()
Within the "execute" method:
Recommended by LinkedIn
3. Finish()
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 :