Passing Parameters to Batch Apex in Salesforce

Passing Parameters to Batch Apex in Salesforce

Constructor can be used for passing parameters to Batch Apex in Salesforce.

Sample Batch Class:

global class SampleBatchClassWithParams implements Database.Batchable<sObject>, Database.Stateful {
    
    private String strParam;
    private Set < Id > setIds;
    
    global SampleBatchClassWithParams( String strParam, Set < Id > setIds ) {
        
        this.strParam = strParam;
        this.setIds = setIds;
        
    }
    
    global Database.QueryLocator start(Database.BatchableContext BC) {
        
        System.debug(
            'strParam is ' + strParam
        );
        System.debug(
            'setIds are ' + setIds
        );
        String strQuery = 'SELECT Id FROM Account LIMIT 1';
        return Database.getQueryLocator( strQuery );
        
    }
    
    global void execute( Database.BatchableContext BC, List < sObject > scope ) {
    }   
    
    global void finish(Database.BatchableContext BC) {
    }
    
}

Executing the Batch:

SampleBatchClassWithParams objBatch = new SampleBatchClassWithParams(
    'testing', 
    new Set < Id > { '001d000001W34vD' }
);
Database.executeBatch(
    objBatch
);

Leave a Reply