FixedTimer.periodic constructor

FixedTimer.periodic(
  1. Duration duration,
  2. void callback()
)

Creates a new FixedTimer.

The callback is invoked repeatedly with duration intervals until canceled.

All FixedTimers with same duration invoke callback at the same time.

Implementation

factory FixedTimer.periodic(Duration duration, void Function() callback) {
  StreamController? controller = _controllers[duration];
  if (controller == null) {
    controller = StreamController.broadcast(
      onCancel: () {
        _controllers.remove(duration)?.close();
        _timers.remove(duration)?.cancel();
      },
    );

    _controllers[duration] = controller;
  }

  Timer? timer = _timers[duration];
  if (timer == null) {
    timer = Timer.periodic(duration, (_) => controller?.add(null));
    _timers[duration] = timer;
  }

  return FixedTimer._(controller.stream.listen((_) => callback()));
}