+ Start a Discussion
rushirushi 

​difference between execute and executebatch

Hello,
  Can anybody tell me the diffrence ​between execute and executebatch in BatchApex?

Thanks in advance
Best Answer chosen by rushi
Andrei KuznetsovAndrei Kuznetsov
Hi,

I know there are lots of technicalities that can be found confusing and to deep. Here how I used it and how I understand it. You create your class that handles you batch logic. In there you have to spcify what you do in Execute method, since it's part of interface. You have to specify Start, Execute and Finish logic. Example:

================================================================
global class BatchContactsSync implements Database.Batchable<sObject>, Database.Stateful, Database.AllowsCallouts {
global Database.QueryLocator start(Database.BatchableContext context){
return Database.getQueryLocator(query);
}
global void execute(Database.BatchableContext context, List<sObject> scope){
try {
for (SObject rec :scope) {
Contact cont = (Contact)rec;
ESO_Update_Contact(cont);
}
}
catch(Exception ex) {
system.debug('------------ BatchContactsSync.execute: Exception : ' + ex);
}
}

global void finish(Database.BatchableContext context){
}
}
=================================================================

When you schedule your batch job you have to pass an instance of the batch class we just defined. And to schedule you batch job you call .batchexecute. This method will also return your batch run ID which you can use in debug logs. Example:

==========================================================================
global class SchedulableBatchContactsSync implements Schedulable
{
global void execute(SchedulableContext ctx){
id batchInstanceId = Database.executeBatch(new batchContactsSync(), 1);
}
}
==========================================================================
Hope it helps, and if it does, please mark my answer as 'best answer'. =) Thanks!