How to achieve a limited number of method executions based on elapsed time?

Viewed 68

I would like to know if there is something like a framework for an execution limit per minute.

Let's say I have an API where I can request 100 times per minute.

If I send a "hello world" in a loop, I would exceed that limit.

For example, something like this:

ExecutionLimiter executer = ExecutionLimiter(executions: 100, duration: Duration(minutes: 1));

while (true) {
  executer.add(() => print(“hello world“));
}

I've found the package queue, but this is only for parallelization.

Thanks for your help.

2 Answers

You can use Timer.periodic to activate a method every given time.

_timer = Timer.periodic(Duration(milliseconds: 600), (Timer t) {
  // Send single api request every 600 ms
});

// Stop sending requests
Future.delayed(const Duration(minutes: 1), () {
  _timer.cancel();
});

Just don't forget to save it in variable and dispose it when you finish using it.

Thanks to the support of Yair Chen, I have created a short example program that executes the function n-times in the given time span. The duration of the execution is taken into account.

import 'dart:async';
import 'dart:math';

List<Instance> instances = [];

int executionLimit = 10;
int apiCallLimitInSeconds = 5;

// for test purposes
int elapsedTime = 0;
int executedFunctions = 0;

main() {
  Timer.periodic(Duration(seconds: 1), (Timer t) {
    instances.removeWhere((element) => element.isInvalid);

    for (int i = 0; instances.length < executionLimit; i++) {
      instances.add(Instance(
          Future.delayed(Duration(milliseconds: Random().nextInt(100)))
              .then((value) => executedFunctions++)));
    }
    //tests again
    elapsedTime++;
    if (elapsedTime % 5 == 0) {
      print(executedFunctions);
    }
  });
}

class Instance {
  Future<void> execute;
  bool isInvalid = false;

  Instance(this.execute) {
    execute.then((value) => Timer(
        Duration(seconds: apiCallLimitInSeconds), () => isInvalid = true));
  }
}
Related