DateTime监听器,监听分钟变化
DateTime listener, listen to the minute changes
我想听分钟的变化,比如如果是6:00
,我想在6:01
的时候听,然后是6:02
的时候,等等。
我可以想到两种方法(不够好)。
我可以设置一个每秒运行一次的 Timer.periodic
并在一分钟内检查变化。
我可以设置一个 Timer.periodic
,它每秒运行一次,直到分钟发生变化,但之后它会自行取消并启动另一个每分钟运行一次的 Timer.periodic
。
有没有比这些解决方法更好的解决方案?
只需获取当前时间,计算到下一分钟的持续时间,然后为该时间量设置 non-periodic Timer
。从那里,您可以创建一个每分钟运行一次的周期性计时器。
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();
});
}
我想听分钟的变化,比如如果是6:00
,我想在6:01
的时候听,然后是6:02
的时候,等等。
我可以想到两种方法(不够好)。
我可以设置一个每秒运行一次的
Timer.periodic
并在一分钟内检查变化。我可以设置一个
Timer.periodic
,它每秒运行一次,直到分钟发生变化,但之后它会自行取消并启动另一个每分钟运行一次的Timer.periodic
。
有没有比这些解决方法更好的解决方案?
只需获取当前时间,计算到下一分钟的持续时间,然后为该时间量设置 non-periodic Timer
。从那里,您可以创建一个每分钟运行一次的周期性计时器。
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();
});
}