Search code examples
fluttereventstimetimerduration

How to set a time-specific event in Flutter?


I am trying to get a switch widget to turn off at a specific time of the day. enter image description here

I have read a lot of the documentations like these

https://stackoverflow.com/questions/15848214/does-dart-have-a-scheduler
https://pub.dev/packages/cron
https://pub.dev/packages/scheduled_timer

All of these which can only allow me to set duration instead of a specific time.

Thus, my only approach right now is by setting up the timer when the switch is turned on. e.g. 8hrs then it turns off.

Problem: If the user turned on the switch late, the time that it turns off will also be delayed.

So is there an actual way to set an event at a specific time + works even after we onstop/terminate the application?


Solution

  • After some time I figured it out.

    Format

      cron.schedule(Schedule.parse('00 00 * * *'), () async {
         print("This code runs at 12am everyday")
      });
    

    More Examples

      cron.schedule(Schedule.parse('15 * * * *'), () async {
         print("This code runs every 15 minutes")
      });
    
    

    To customize a scheduler for your project, read this