I need to do a batch which calls itself until a condition is true. I don't know how to start. I've tried some things but I got an infinite loop.

The idea is:

  1. I have a start date Ex: 2019-01-01
  2. Make some things with that date
  3. Check if the date is the current date. If true, finish. If false, add 1 day to the start date and run again. (in the 2nd lap the start date would be 2019-01-02, etc.)

How can I achieve this?. I can't do it on a do-while loop, it's neccesary do it in an apex batch.

I hope you can help me. Thanks in advance

  • do you want to run execute the batch once in a day? Nov 12, 2019 at 13:32
  • no, I need to cover an interval of dates every day
    – Javier
    Nov 12, 2019 at 13:38
  • ok but batch will run only once in a day, right? Nov 12, 2019 at 13:48

1 Answer 1


You can call batch from the previous batch finish() method. For example,

Initial step to call in developer console or anonymous is Database.executeBatch(new RecursiveBatch(Date.valueOf('2019-01-01')));

Then you can use this stub.

public class RecursiveBatch implements Database.Batchable<sObject>, Database.AllowsCallouts, Database.Stateful {
private final Date passedDate;

public RecursiveBatch(Date passedDate) {
    this.passedDate = passedDate;

public Database.QueryLocator start(Database.BatchableContext BC) {
    return Database.getQueryLocator( < QUERY >);

public void execute(Database.BatchableContext BC, List<sObject> scope) {


public void finish(Database.BatchableContext BC) {
    if(Date.today() <= this.passedDate) {
        Database.executeBatch(new RecursiveBatch(passedDate.addDays(1)));


  • It works! Thank you so much
    – Javier
    Nov 13, 2019 at 11:57

You must log in to answer this question.

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