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
vijay kumar kvijay kumar k 

how to write the execute method will run at finish method in bathch class

i want to know how many times the execute method will run , so it is poossible to know using finish method.i mean after execute the batch class ,finnally i want see how many times my execute method will run. please give me simple example
Sandeep YadavSandeep Yadav
H Vijay,
How many times execute method will run it totally depends on the Batch Size and number of the Records retrieved in start method.
database.executeBatch(yourClassInstance, batchSize).
Here,Default batch size is 200 i.e. execute method will process 200 records at a time. If your start method returns 1000 records  then execute method will run 5 times.

You can use a Integer variable that will count how many times execute method will run. Here is the simple example of batch class.
global class AccountBatch implements Database.Batchable<sObject>{
    
    public Integer i=0;
    global Database.QueryLocator start(Database.BatchableContext bc) {
        return Database.getQueryLocator('select id,name,rating from account limit 10');    
    }
    
    global void execute(Database.BatchableContext bc, List<Account> scope){
        i++;
        List<Contact> conList = new List<Contact>();
        for(Account ac : scope){
            conList.add(new Contact(
            	lastname = ac.Name+ 'Conta',accountId = ac.Id
            ));
            
        }
        system.debug('<<frequenccy of execute method>>'+i);
    }
    
    global void finish(Database.BatchableContext bc){
       
	}

}

You can run this batch class from Anonymous window  by executing this code--
database.executeBatch(new AccounBatch(),1);

Mark this answer as solved if it helps you and let me know for further query
Regards
Sandeep
vijay kumar kvijay kumar k
thank you for replay,
coming to your point, If your start method returns 1000 records  then execute method will run 5 times.ok ,i want that anser at finish method. i mean how to show that number(5 as a answer ,it is every one knows) in system.debug(). please help me to programatically your execute method will run '5' times.

 
Sandeep YadavSandeep Yadav
Hi Vijay,
For getting result of i into finish method you have to retain value of i. For this you have to implement Dtatbase.stateful Interface.
 
global class AccountBatch implements Database.Batchable<sObject>,Database.stateful{ 

}
In finish method you can debug i.

Hope its help you.
Regards
Sandeep