function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Sonali Rawat 6Sonali Rawat 6 

Hi all, I want to schedule my batch of size 1000 into 5 chunks of size 200 and I want to schedule all the 5 chunks at different times. How can I do it?

Best Answer chosen by Sonali Rawat 6
Eswar Venkat 2Eswar Venkat 2

@Sonali 

 

public class BatchScheduler {
    public static void scheduleBatch() {
        Datetime startTime = Datetime.newInstanceGmt(2023, 5, 4, 0, 0, 0); // Set the start time for the first batch
        for (Integer i = 1; i <= 5; i++) {
            MyBatch batch = new MyBatch();
            batch.jobName = 'My Batch Job #' + i;
            batch.query = 'SELECT Id FROM Account LIMIT 200 OFFSET ' + ((i - 1) * 200);
            System.schedule(batch.jobName, getCRONString(startTime), batch);
            startTime = startTime.addMinutes(30); // Schedule the next batch 30 minutes later
        }
    }
    
    private static String getCRONString(Datetime startTime) {
        return startTime.second() + ' ' + startTime.minute() + ' ' + startTime.hour() + ' ' + startTime.day() + ' ' + startTime.month() + ' ? ' + startTime.year();
    }
}
 

 

Call the scheduleBatch method to schedule your batch job:

 

BatchScheduler.scheduleBatch();
 

This will schedule your batch job to process 1000 records in 5 chunks of size 200, with each chunk being processed 30 minutes after the previous one or you can increase the timer