【问题标题】:Difference between cron plugin and Timer.periodic in FlutterFlutter 中 cron 插件和 Timer.periodic 的区别
【发布时间】:2020-09-06 09:55:02
【问题描述】:
**every 5 seconds something will be called**

Timer.periodic(Duration(seconds: 5), (timer) {
  //something();

});

**every 1 minute something() will be called.**
  var cron = new Cron();
cron.schedule(new Schedule.parse('*/1 * * * *'), () async {
 // something();

});

但如果应用不再在内存中,两者都不会执行作业。

【问题讨论】:

    标签: flutter dart timer background scheduling


    【解决方案1】:

    Cron 优于 Timer 的优势在于,使用 Cron 语法,您可以指定复杂的时间间隔,而不仅仅是恒定的持续时间间隔。

    例如,使用 Timer 很难在每天的特定时间(例如下午 6:05)执行一个函数,因为它取决于你的开始时间,它会添加一个恒定的持续时间,而不像 Cron 你可以放:

    var cron = new Cron();
    cron.schedule(new Schedule.parse('5 6 * * *'), () async {
    // something();
    });
    

    总而言之,如果您的目标只是在固定间隔内重复一项任务,请使用 Timer,如果您的目标更复杂,例如在工作日的下午 6 点每 2 个月重复一次任务,您可能需要 Cron。

    var cron = new Cron();
    cron.schedule(new Schedule.parse('0 6 * */2 MON-FRI'), () async {
    // something();
    });
    

    这里是一个了解更多关于 Cron 语法的链接:corn syntax

    【讨论】:

    • 感谢您的回答我很感激,但是即使应用程序不再在内存中,也有一种方法可以安排工作
    • 如果我的第一个答案回答了您的第一个问题,请点赞。对于你的第二个问题:不,在 Flutter 中这是不可能的,但你可以做的是在你的应用程序开始时启动你的回调函数(你在 cron 中定期重复的那个)以掩盖所有错过的滴答声。
    猜你喜欢
    • 1970-01-01
    • 2014-03-14
    • 2017-06-14
    • 1970-01-01
    • 2019-11-15
    • 1970-01-01
    • 2023-02-04
    • 1970-01-01
    • 2014-03-04
    相关资源
    最近更新 更多