How do you pass runtime parameters into a Batch Apex class prior to execution?
Answer
Basics: Database.executeBatch takes only the batch instance and the scope size, so everything the job needs (filters, record Ids, flags, a user to notify) has to be set on the object before you submit it.
How it works:
- Define a constructor with the parameters.
- Save them in private instance fields.
- Use them in
start()to build the query (via bind variables) and later inexecute(). - Instantiate and launch:
Database.executeBatch(new MyBatch(args), 200).
Advanced / deep dive: The batch instance is serialized between start, each execute, and finish, so fields must be serializable; non-serializable members need the transient keyword and rebuilding. Instance fields set in the constructor are retained for every chunk without needing Database.Stateful, because they are part of the serialized instance; Stateful is only needed for values that you change inside execute() and want to see in later chunks. Large parameters (for example thousands of Ids) inflate every serialization, so pass a filter or a staging record Id instead. From a scheduled class, build the job inside Schedulable.execute() and read parameters from Custom Metadata so admins can change them. Use bind variables rather than string concatenation to avoid SOQL injection.
Code / config example:
public class RegionRecalcBatch implements Database.Batchable<SObject> {
String region;
Date since;
{
.region = region;
.since = since;
}
Database.QueryLocator {
Database.getQueryLocatorWithBinds(
,
<String,Object>{ => region, => since },
AccessLevel.USER_MODE);
}
{ }
{}
}