Monday, 9 October 2023

Passing Parameter Id to Batch Class

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 String query;
    
     
    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+'\''; }
     //Method to get the data to be proceesed 
    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:
To Run One Record:
TestBatch objcls=new TestBatch('--Acc Id--');
database.executebatch(objcls,1);


To Run normal batch/all records:
TestBatch objcls=new TestBatch('--Acc Id--');
database.executebatch(objcls,1);