I need to pass the query to the batch class while scheduling it. How could i send the query as a parameter from the schedule class to batch class?
1 Answer
You can pass parameters to batch class when instantiating it, for example
String query = 'SELECT Id FROM Account';
SomeBatchClass batch = new SomeBatchClass(query);
Database.executeBatch(batch);
and create custom constructor in batch:
public class SomeBatchClass implements Database.batchable<sObject>{
private String query;
public SomeBatchClass(String query) {
this.query = query;
}
public Database.QueryLocator start(Database.BatchableContext BC) {
return Database.query(this.query);
}
// other code
}
I edited code due to Felix's comment.
-
salesforce.stackexchange.com/a/103224/68413 If you do not use database.stateful then any changes made to the parameter during the execute method are not persisted across batches and the next execute method will be the original value. Jun 6 at 21:11
-
2Just one remark: "global" is to be avoided, "public" to be preferred. Jun 6 at 21:14
-
1
-