[SalesForce] Passing a parameter to batchable class

I have the following batchable class:

global class batchableClassName implements Database.Batchable<sObject>, Database.AllowsCallouts
{
    global Database.QueryLocator start(Database.BatchableContext BC)
    {
        String query = 'SELECT Company, Website FROM Lead';

        return Database.getQueryLocator(query);
    }
    global void execute(Database.BatchableContext BC, List<Lead> scope)
    {
        for(Lead l : scope)
        {
                    Class.function(l.Website);
        }
        update scope;
    }
    global void finish(Database.BatchableContext BC) {
    }
}

Instead of hard typing the SOQL query within the batchable class I would like to be able to pass a query to the function when running it, for example:

batchableClassName.batchableClassFunction('SELECT Company, Name FROM Lead WHERE Status = \'Active\'');

I found some info about this on Stack Exchange but struggle to apply it to my particular problem.

Best Answer

The typical way to do this is to write a constructor, and place the desired variables into your class. Here's the minimum changes you could make:

global class batchableClassName implements Database.Batchable<sObject>, Database.AllowsCallouts
{
    String query;
    global batchableClassName(String queryString) 
    {
        query = queryString;
    }
    global Database.QueryLocator start(Database.BatchableContext BC)
    {
        return Database.getQueryLocator(query);
    }
    global void execute(Database.BatchableContext BC, List<Lead> scope)
    {
        for(Lead l : scope)
        {
                    Class.function(l.Website);
        }
        update scope;
    }
    global void finish(Database.BatchableContext BC) {
    }
}

Which would be queued for execution like this:

Database.executeBatch(new batchableClassName('SELECT Company, Website FROM Lead'));
Related Topic