我的应用也有类似的情况,我必须在一天中的某个时间触发一个事件。
我们不能使用定时器功能,因为一旦应用程序关闭,操作系统就会杀死应用程序,定时器也停止运行。
所以我们需要在某个地方节省我们的时间,然后检查它,如果节省的时间现在已经到了。
首先,我创建了一个 DateTime 实例并将其保存在 Firestore 上。您也可以将该 DateTime 实例保存在本地数据库中,例如:SQFlite 等。
//DateTime instance with a specific date and time-
DateTime atFiveInEvening;
//this should be a correctly formatted string, which complies with a subset of ISO 8601
atFiveInEvening= DateTime.parse("2021-08-02 17:00:00Z");
//Or a time after 3 hours from now
DateTime threehoursFromNow;
threeHoursFromNow = DateTime.now().add(Duration(hours: 3));
现在使用 ID 将此实例保存到 FireStore-
saveTimeToFireStore() async {
await FirebaseFirestore.instance.collection('users').doc('Z0ZuoW8npwuvmBzmF0Wt').set({
'atFiveInEvening':atFiveInEvening,
});
}
现在在应用打开时从 Firestore 中检索此设置时间-
getTheTimeToTriggerEvent() async {
final DocumentSnapshot doc =
await FirebaseFirestore.instance.collection('users').doc('Z0ZuoW8npwuvmBzmF0Wt').get();
timeToTriggerEvent= doc['atFiveInEvening'].toDate();
//Now use If/Else statement to know, if the current time is same as/or after the
//time set for trigger, then trigger the event,
if(DateTime.now().isAfter(timeToTriggerEvent)) {
//Trigger the event which you want to trigger.
}
}
但是在这里我们必须一次又一次地运行函数 getTheTimeToTriggerEvent() 来检查时间是否到了。