How to trigger a function at midnight

146

As documented here.

DateTime current = DateTime.now();
Stream timer = Stream.periodic( Duration(seconds: 1), (i) {
       current = current.add(Duration(seconds: 1));
      return current;
    });

    timers.listen((data)=> print(data));

Otherwise on open, just evaluate for date/time.

Share:
146
Joe
Author by

Joe

Updated on January 03, 2023

Comments

  • Joe
    Joe over 1 year

    My app should trigger the function "dayChange()" whenever one of the two cases is true:

    1. Midnight has passed since the app was last active (opening or resuming)
    2. The app is active at midnight

    "dayChange()" puts a new object in a list and saves that list to my instance of shared preferences.

    What I need: I'm not aksing for a complete solution (hence no code), but some basic understanding and a direction to Google in.

    Where I am at right now: I'm close to a solution for 1. I save DateTime.now() and load it via SharedPreferences everytime the app is opened. I then check if the day has changed. I'm not quite sure how to handle resuming yet, but I'm confident I can figure it out by googling life cycle stuff.

    For 2 things get more complicated.

    • I had a somewhat working solution where I start a timer that performs a check every second; but it was bugy as heck and does not feel elegant. It's still my most promising approach so far.
    • When googling how to program alarms with flutter, I get into very tricky territory fast (having to do it differently on iOS and Android; accessing system stuff; handling permissions; all beyond what I have done so far).
    • I found something about a thing called "applicationSignificantTimeChange" ... but some Googling later it feels like a total deadend or I'm missing another search term.

    What are good approaches to this? I'm willing to dig deeper to solve the issue, but I don't want to go on a wild goose hunt without knowing a goose is what I actually need.

  • Joe
    Joe about 2 years
    Hey, thanks for answering! Could I not just check whether the day is still the same than a second before inside of that stream? I would need an initial DateTime value and then perform a check every second and update the initial value with DateTime.now. Maybe along those lines: int daysSinceLastUse = nowDate.difference(thenDate).inDays; ... and if that is >0 I trigger my function? That's the approach I took last time, but it ended up beign buggy. If it is the right road to take, I'll investigate further.