Home > Software design >  DateTime listener, listen to the minute changes
DateTime listener, listen to the minute changes

Time:05-21

I want to listen to the minute changes, for example, if it is 6:00, I want to listen when it is 6:01 and then 6:02, and so on.

There are two ways (not good enough) that I can think of doing this.

  1. I can setup a Timer.periodic which runs every second and check for the change in minute.

  2. I can setup a Timer.periodic which runs every second till the minute gets changed but after that it cancels itself and fires up another Timer.periodic which runs every minute.

Is there any better solution than these workarounds?

CodePudding user response:

Just get the current time, compute the duration until the next minute, and set a non-periodic Timer for that amount of time. from there, you can create a periodic timer that runs every minute.

void executeOnMinute(void Function() callback) {
  var now = DateTime.now();
  var nextMinute =
      DateTime(now.year, now.month, now.day, now.hour, now.minute   1);
  Timer(nextMinute.difference(now), () {
    Timer.periodic(const Duration(minutes: 1), (timer) {
      callback();
    });

    // Execute the callback on the first minute after the initial time.
    //
    // This should be done *after* registering the periodic [Timer] so that it
    // is unaffected by how long [callback] takes to execute.
    callback();
  });
}
  • Related