Timers in Dart

In Dart, we can use timers to execute code at some point in the future or repeatedly at some interval. Let’s explore how to use timers in Dart.

import 'dart:async';

void main() {
  // Timers represent a single event in the future. You
  // tell the timer how long you want to wait, and it
  // provides a Future that will complete at that time.
  // This timer will wait 2 seconds.
  Timer timer1 = Timer(Duration(seconds: 2), () {
    print('Timer 1 fired');
  });

  // The `await` keyword blocks until the Future completes,
  // indicating that the timer fired.
  timer1.future.then((_) {
    print('Timer 1 completed');
  });

  // If you just wanted to wait, you could have used
  // Future.delayed. One reason a timer may be useful is
  // that you can cancel the timer before it fires.
  // Here's an example of that.
  Timer timer2 = Timer(Duration(seconds: 1), () {
    print('Timer 2 fired');
  });

  // Cancel the timer
  timer2.cancel();
  print('Timer 2 cancelled');

  // Give the timer2 enough time to fire, if it ever
  // was going to, to show it is in fact cancelled.
  Future.delayed(Duration(seconds: 2), () {
    print('Finished waiting');
  });
}

To run this Dart program:

$ dart run timers.dart
Timer 2 cancelled
Timer 1 fired
Timer 1 completed
Finished waiting

In this example, we create two timers. The first timer fires after 2 seconds, while the second timer is cancelled before it has a chance to fire.

Note that Dart’s Timer class is slightly different from Go’s timer. In Dart, you provide a callback function that will be executed when the timer fires, instead of using a channel.

The Future.delayed method is used at the end to give enough time for the timers to complete (or not complete, in the case of the cancelled timer) before the program exits.