start method

void start(
  1. void sendMessage(
    1. Msg
    )
)

Starts the repeating timer.

Messages are sent through the provided sendMessage callback.

Implementation

void start(void Function(Msg) sendMessage) {
  // Calculate time until next interval boundary
  final now = DateTime.now();
  final intervalMs = interval.inMilliseconds;
  final msIntoInterval = now.millisecondsSinceEpoch % intervalMs;
  final msUntilNext = intervalMs - msIntoInterval;

  // First tick at next boundary
  _starter?.cancel();
  _timer?.cancel();
  _starter = Timer(Duration(milliseconds: msUntilNext), () {
    // If stop() was called before the first tick, do nothing.
    if (_starter == null) return;
    _tick(sendMessage);
    // Then repeat at interval
    _timer = Timer.periodic(interval, (_) => _tick(sendMessage));
  });
}