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

Batch Apex: forcing a time spread for the execution of individual transactions

When submitting a Batch, Apex determines how to split the batch in individual transactions, using 200 as a standard number of records to be processed by each transaction, unless otherwise specified.


My application makes HTTP callouts to the Twitter API, which imposes limits on how many calls can be made for each 15 minutes time windows.  In my case this limit is 360 calls per 15 minutes.


My question is: can I impose a "time spread" or "schedule" for individual transactions to be processed ? For example, if Apex creates 10 transactions for my batch, I would like to make sure only 5 run now, followed by the other 5 in the following hour.


I want to know if this is possible before I explore more exotic solutions.


Thank you in advance for your ideas and suggestions !

JP Lavoie

The short answer is no.

The long answer is yes, but...

What you'll need is a Schedulable class, Batchable class, and Iterable class (they can be the same class, if you want, or split in 2 or 3 parts).

The Iterable class should have a counter to control the number of calls in maximum that will be produced. It can be controlled to terminate early if there is no more data.

The Batchable class' finish method should invoke a scheduled call 15 minutes out that calls the Schedulable class.

The Schedulable class simply calls the Batchable class when its timer kicks off.

So, it's probably closer to the "more exotic solution" you described, as there is no thread control (e.g. Thread.sleep, as in Java) to keep the batch running indefinitely.

Thank you for your reply !

I need one clarification about the iterable class.  I'm not sure how to handle it.  I am sending a SOQL query as the parameter for the batch.  As an example, the query returns 500 records.  Since I cannot make more than 10 callouts per "transaction", I call the batch with "10" as parameter with the query.  This hence generate 50 transactions.  How can I control that, collectively, I can exit processing when the total of record processed reaches 350 ?

If you can provide a link that shows an example of an iterable class used in the context of a batch, that would be great !

Thank you again,