Timer的官方文档资料
1.单次运行的定时器
factory Timer(Duration duration, void Function() callback) {
if (Zone.current == Zone.root) {
return Zone.current.createTimer(duration, callback);
}
return Zone.current
.createTimer(duration, Zone.current.bindCallbackGuarded(callback));
}
void countDown() {
print("当前时间=======${DateTime.now()}");
Timer timer = Timer(const Duration(seconds: 5), (){
print("5秒后执行定时器======${DateTime.now()}");
setState(() {
_counter++;
});
});
}
如果你立刻执行一个定时器,可以调用run方法:
static void run(void Function() callback) {
new Timer(Duration.zero, callback);
}
static const Duration zero = Duration(seconds: 0);
run() :方法的实质是创建一个时间为0的定时器 创建定时器的时候, 如果传入的时间是负数或则0,这两种情况都当成时间是0,会立刻执行定时器,这一点官方文档是有说明的
2. 重复运行定时器
factory Timer.periodic(Duration duration, void callback(Timer timer)) {
if (Zone.current == Zone.root) {
return Zone.current.createPeriodicTimer(duration, callback);
}
var boundCallback = Zone.current.bindUnaryCallbackGuarded<Timer>(callback);
return Zone.current.createPeriodicTimer(duration, boundCallback);
}
void countDown2() {
print("当前时间=======${DateTime.now()}");
Timer timer = Timer.periodic(const Duration(seconds: 3), (timer) {
setState(() {
print("3秒后执行定时器======${DateTime.now()}");
_counter ++;
});
if (_counter == 5) {
timer.cancel();
print("执行5次之后停止定时器");
}
});
}
bool get isActive; 判断定时器,是否处于活跃状态
|