1

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?

Ashley Medway
  • 7,151
  • 7
  • 49
  • 71
Jeff
  • 253
  • 1
  • 2
  • 10
  • 1
    you can add another condition using `DateTime.now()`. DateTime has helper functions like `isAfter` and `isBefore` you can check that with another datetime if it's after or before – Pokaboom Jul 11 '22 at 08:21

2 Answers2

2

You can try to do something like this:

I'll simplify the specific time into :

...
  var setTime = DateTime.utc(2022, 7, 11, 8, 48, 0).toLocal();
  StreamSubscription? subscription;
...

Then you can assign a periodic stream listener:

...
  // periodic to run every second (you can change to minutes/hours/others too)
  var stream = Stream.periodic(const Duration(seconds: 1), (count) {
      //return true if the time now is after set time
      return DateTime.now().isAfter(setTime);
  });

  //stream subscription
  subscription = stream.listen((result) {
      // if true, insert function and cancel listen subscription
      if(result){
        print('turn off');
        subscription!.cancel();
      }
      // else if not yet, run this function
      else {
        print(result);
      }
  });
...

However, running a Dart code in a background process is more difficult, here are some references you can try:

https://medium.com/flutter/executing-dart-in-the-background-with-flutter-plugins-and-geofencing-2b3e40a1a124

https://pub.dev/packages/flutter_background_service

I hope it helps, feel free to comment if it doesn't work, I'll try my best to help.

Cubelated
  • 47
  • 8
1

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

Jeff
  • 253
  • 1
  • 2
  • 10