runPeriodically static method
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 offunc. It receives theTimerand 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);
});
}