【问题标题】:How to execute a method in a certain time in flutter?如何在flutter中在一定时间内执行一个方法?
【发布时间】:2020-12-12 09:32:32
【问题描述】:

如何在固定时间执行方法,就像我想在下午 2:30 运行方法一样。我知道定时器功能,但是长时间运行定时器功能是个好主意吗?同样,该方法将在一天内被多次调用。

已编辑: 我试过android_alarm_manager,但不适合我的情况。 (因为我需要从回调方法调用 bloc )。此外,我不需要在后台运行我的应用程序。

任何帮助将不胜感激

【问题讨论】:

  • 如果您现在了解 DateTime ,您可以手动制作 ..
  • 你能解释一下吗!
  • 即使应用程序不再在前台,您也没有告诉我们是否应该在后台执行此功能。如果你确实需要它(比如警报),那么你应该看看Isolate 和这个doc regarding background processes
  • 我不需要在后台运行这个应用程序。谢谢,我会编辑问题。

标签: flutter dart


【解决方案1】:
DateTime yourTime;
VoidCallback yourAction;
Timer(yourTime.difference(DateTime.now()), yourAction);

【讨论】:

    【解决方案2】:

    我的应用也有类似的情况,我必须在一天中的某个时间触发一个事件。

    我们不能使用定时器功能,因为一旦应用程序关闭,操作系统就会杀死应用程序,定时器也停止运行。

    所以我们需要在某个地方节省我们的时间,然后检查它,如果节省的时间现在已经到了。

    首先,我创建了一个 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() 来检查时间是否到了。

    【讨论】:

      猜你喜欢
      • 2020-10-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-02
      • 2013-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多