You are on page 1of 3

Batch Apex

To use batch Apex, you must write an Apex class that implements the Salesforce-provided
interface Database.Batchable, and then invoke the class programmatically.

To monitor or stop the execution of the batch Apex job, from Setup,
click Monitoring | Apex Jobs or Jobs | Apex Jobs.

Implementing the Database.Batchable Interface:-

The Database.Batchable interface contains three methods that must be implemented:

i) Start Method

Global Database.QueryLocator start(Database.BatchableContext bc)


{
}

The start method is called at the beginning of a batch Apex job. Use the start method to collect
the records or objects to be passed to the interface method execute.
ii) Execute Method
Global void execute(Database.BatchableContext bc,list<P>)
{
}
The execute method is called for each batch of records passed to the method. Use this method to do
all required processing for each chunk of data.

This method takes the following:

 A reference to the Database.BatchableContext object.

 A list of sObjects, such as List<sObject>, or a list of parameterized types. If you are using
a Database.QueryLocator, the returned list should be used.

Batches of records execute in the order they are received from the start method.

The finish method is called after all batches are processed. Use this method to send confirmation emails or
execute post-processing operations.

Note:-

Each execution of a batch Apex job is considered a discrete transaction. For example, a batch Apex job that contains
1,000 records and is executed without the optional scopeparameter from Database.executeBatch is
considered five transactions of 200 records each. The Apex governor limits are reset for each transaction. If the first
transaction succeeds but the second fails, the database updates made in the first transaction are not rolled back.

Classification: GECRB Birlasoft GDC Public


Example:-

Global class AccountUpdateBatch implements Database.Batchable<Account>

List<account> recordstoupdate = new list<account>();

global Database.QueryLocator start(Database.BatchableContext bc)

Return Database.getQueryLocator(‘Select Id,Name,Industry from Account’);

Global void execute(Database.BatchableContext bc,list<Account> records)

For(Account a:records)

a.Industry=’Agriculture’;

recordstoupdate.add(a);

Update recordstoupdate;

Global void finish(Database.BatchableContext bc)

Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();

Mail.settoaddresses();

Mail.setSubject(‘Records successfully processed’);

Mail.setplaintextbody(‘Batch has completed all the records processing.Thanks’);

Messaging.sendEmail(new Messaging.singleEmailMessage[] {mail});

Executing batch apex:-

Classification: GECRB Birlasoft GDC Public


AccountUpdateBatch a = new AccountUpdateBatch ();

a.query='select Id,Name,Industry from Account';

Id Jobid=database.executebatch(a);

Classification: GECRB Birlasoft GDC Public

You might also like