Hello everyone,
In this post I want to show you, how to pass parameters to batch apex class. This is very useful when you want to test or execute batch on parameter based records.
Passing parameter to batch apex using constructor
Here is the example that helps you to pass parameter in batch apex.
Using Class Constructor
global
class
TestBatch
implements
Database.batchable<sObject>, Database.Stateful<Sobject>{
global TestBatch(){ query = 'SELECT ID, Name FROM Account where Name!= null'; } global TestBatch(Id recordId){ query = 'SELECT ID, Name FROM Account where Name != null and id =\''+recordId+'\''; }
global database.Querylocator Start(Database.BatchableContext bc){
return
Database.getQueryLocator(query);
}
//Method to execute the batch
global
void
execute(Database.BatchableContext bc, Sobject[] scope){
// Execute method logic
}
//Method to be called after the excute
global
void
finish(Database.BatchableContext bc){
// Finish method logic
}
}
To Execute: