1

I was wondering if it's a good idea or even possible to call multiple batch jobs from one scheduled class. Every year at the beginning of the year we want to create records for each sales rep for each month based on the ForecastingQuotas we create at the beginning of the year. Every rep gets 12 quotas made (1 for each month), and then I want to run a batch job to query these quotas and create a record for each rep for each month containing that quota information. The issue is the amount of reps/quotas are always changing, so 1 batch could contain quotas for every rep for January, as well as a few quotas for every rep for February. I'd like to simplify the code so each batch job only deals with 1 month. We don't have 200+ sales reps so each batch would only run once, but we want this to be scalable for the future.

I was thinking instead of writing the code to be able to handle multiple months in the batch class, I'd run 12 queries from the scheduled class (1 for each month) and send each list to a separate instance of the batch class to only be coded to work for one month.

So I'd loop through an integer 12 times and call the batch class, passing the integer to each instance of the class. In the class, I'd only query the quotas where CALENDAR_MONTH(StartDate) = integer, so each instance would only pull back quotas for this month. I know this kind of breaks the rule of "never put a query in a for loop", but in this case it iterates only 12 times and each query is part of a batch class.

Would this work, or would I be better off writing logic to handle multiple months and just call 1 instance of the batch class?

Thanks!

1 Answer 1

2

You can't call Database.executeBatch that many times, so you'd end up having to schedule 12 copies of your class (or 12 different classes) for your scheduleable methods, on top of the 12 batch classes. Instead, perhaps you could make your batch size 1, and pass in the calendar month for each:

public class BuildQuotas implements Database.Batchable<Integer>, Schedulable {
  public void execute(ScheduableContext context) {
    Database.executeBatch(this, 1); // One month per execute
  }
  public Integer[] start(Database.BatchableContext context) {
    return new Integer[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };
  }
  public void execute(Database.BatchableContext context, Integer[] scope) {
    Integer calendarMonth = scope[0];
    // Do your work here
  }
  public void finish(Database.BatchableContext context) {
  }
}
1
  • Thanks for the suggestion. I was hoping not to go 1 by 1 but this is definitely an option that would simplify the code quite a bit. Commented Apr 18, 2017 at 20:00

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .