runPeriodically static method

Timer runPeriodically({
  1. required Duration interval,
  2. required void onExecute(
    1. Timer timer,
    2. int count
    ),
})

Executes a function periodically with the given interval.

This method provides a callback onExecute that gets called after each interval, passing the Timer and the count of executions.

Parameters:

  • interval: The duration between each execution of the function.
  • onExecute: A callback function that gets called after each execution of func. It receives the Timer and the count of executions.

Example:

Timer timer = TimeUtils.runPeriodically(
  interval: Duration(seconds: 1),
  onExecute: (timer, count) {
    print('Executed $count times');
    if (count >= 5) {
      timer.cancel(); // Stop after 5 executions
    }
  }
);

Implementation

static Timer runPeriodically({
  required Duration interval,
  required void Function(Timer timer, int count) onExecute,
}) {
  var count = 0;
  return Timer.periodic(interval, (timer) {
    count++;
    onExecute(timer, count);
  });
}