function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Narasimha LNarasimha L 

What are the methods in batch apex and which method runs in synchronous mode?

Hi Dev's

Q). What are the methods in batch apex and which method runs in synchronous mode?

Regards
Narasimha
Leo10Leo10
Hi Narasimha
You can refer this link for methods in batch apex 
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_batch_interface.htm

start method is the synchronous method in batch apex

Thank you
NagendraNagendra (Salesforce Developers) 
Hi Narasimha,

Batch Apex is exposed as an interface that must be implemented by the developer. Batch jobs can be programmatically invoked at runtime using Apex.

Need of Batch Apex: - As you all might know about the salesforce governor limits on its data. When you want to fetch thousands of records or fire DML on thousands of rows on objects it is very complex in salesforce and it does not allow you to operate on more than certain number of records which satisfies the Governor limits.

But for medium to large enterprises, it is essential to manage thousands of records every day. Adding/editing/deleting them when needed.
Salesforce has come up with a powerful concept called Batch Apex. Batch Apex allows you to handle more number of records and manipulate them by using a specific syntax.

We have to create a global apex class which extends Database.Batchable Interface because of which the salesforce compiler will know, this class incorporates batch jobs. Below is a sample class which is designed to delete all the records of Account object (Let us say your organization contains more than 50 thousand records and you want to mass delete all of them).

Methods in Batch Apex:

Start method


          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.

Syntax: global (Database.QueryLocator | Iterable<sObject>) start(Database.BatchableContext bc) {}

 This method returns either a Database.QueryLocator object or an iterable that contains the records or objects being passed into the job.

 
Execute Method

          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.

Syntax: global void execute(Database.BatchableContext BC, list<P>){}

 
This method takes the following:
o    A reference to the Database.BatchableContext object.
o    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.
 
Finish Method

Syntax: global void finish(Database.BatchableContext BC){}

 
The finish method is called after all batches are processed. Use this method to send confirmation emails or execute post-processing operations.
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 scope parameter 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.
 
Examples:-
global class deleteAccounts implements Database.Batchable
{
global final String Query;
global deleteAccounts(String q)
{
Query=q;
}
 
global Database.QueryLocator start(Database.BatchableContext BC)
{
return Database.getQueryLocator(query);
}
 
global void execute(Database.BatchableContext BC,List scope)
{
List <Account> lstAccount = new list<Account>();
for(Sobject s : scope)
{
 Account a = (Account)s;
lstAccount.add(a);
}
Delete lstAccount;
}
 
global void finish(Database.BatchableContext BC)
{
                //Send an email to the User after your batch completes
                Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
String[] toAddresses = new String[] {‘sforce2009@gmail.com’};
mail.setToAddresses(toAddresses);
mail.setSubject('Apex Batch Job is done‘);
mail.setPlainTextBody('The batch Apex job processed ');
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
}
}
 
//This is how the batch class is called.
id batchinstanceid = database.executeBatch(new deleteAccounts(‘select Id from Account’))
Note: As batch apex runs in asynchronous mode of execution all the methods in batch apex runs in asynchronous mode.

Please mark this as best answer if this helps.

Best Regards,
Nagendra.
Rahul YadavanshRahul Yadavansh
global class BatchClassTemplate implements Database.Batchable<SObject>,Database.Stateful {
    //Database.Stateful: Maintain state of variables Eg: PositionBatch 
    //records to be processed
    public Database.QueryLocator start(Database.BatchableContext bc){
        return Database.getQueryLocator([Select Id from Account]);
    }
    //login that will be applied to each records in the scope
    global void execute(Database.BatchableContext info, List<SObject> scope){
        
    }
    //logic that will run once
    global void finish(Database.BatchableContext bc){
    
    }
}

The batch runs in Asyschronous mode and so does all the three methods. 
Nishad KNishad K
Hi Narasimha,

All execute methods for batches within a batch job are synchronous so they will not "trip" over each other.

Regards,
Nishad KNishad K
if it's resolved, mark the answer  and keep the community clean!!