0

Is it possible to have multiple queries in dynamic batch apex? After one query is finished up - I would like it to start another batch with another query.

  String Contacts_Created_TR_120_Query = 'SELECT CreatedByID SDR_ID, COUNT( id ) result FROM Contact Where CreatedDate = LAST_N_DAYS:120 AND CreatedById in :ListOfIDs GROUP BY CreatedById';
    DynamicBatchApexAR batch1_TR120      =   new DynamicBatchApexAR('SDR_ID', 'result', 'Contacts_Created_TR_120__c', Contacts_Created_TR_120_Query, SDR_IDs);

    String Accounts_Created_TR_120_Query = 'SELECT CreatedByID SDR_ID, COUNT( id ) result FROM Account Where CreatedDate = LAST_N_DAYS:120 AND CreatedById in :ListOfIDs GROUP BY CreatedById';
    DynamicBatchApexAR batch2_TR120      =   new DynamicBatchApexAR('SDR_ID', 'result', 'Accounts_Created_TR_120__c', Accounts_Created_TR_120_Query, SDR_IDs);

Trying to avoid the above code.

4

Sure. You can chain into a second batch from the finish() method of your first batch.

Starting with API version 26.0, you can start another batch job from an existing batch job to chain jobs together. Chain a batch job to start a job after another one finishes and when your job requires batch processing, such as when processing large data volumes. [...]

You can chain a batch job by calling Database.executeBatch or System.scheduleBatch from the finish method of the current batch class. The new batch job will start after the current batch job finishes.

If the second batch class requires input other than the results of the first batch class, the code that initiates the process can pass parameters to the first batch which it stores in instance variables (implementing Database.Stateful) and then passes on to the second batch:

public BatchOne(String myParameter1, myParameter2) {
    this.myParameter1 = myParameter1;
    this.myParameter2 = myParameter2;
}

public void finish(Database.BatchableContext bc) {
    Database.executeBatch(new BatchTwo(myParameter2));
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.