How to execute a method in a certain time in flutter?

Viewed 3038

How can I execute a method in a fixed time like I want to run a method at 2:30 pm. I know about Timer function, But is it a good idea to run a timer function such a long time? Again the method will be called many times in a day.

Edited: I have tried android_alarm_manager but it is not suitable for my condition. (because I need to call bloc from the callback method). Moreover I don't need to run my app in background.

Any help will be appreciated

3 Answers
DateTime yourTime;
VoidCallback yourAction;
Timer(yourTime.difference(DateTime.now()), yourAction);

I had a similar condition for my app, where I had to trigger an event at a certain time in a day.

We cannot use Timer function, because once the app is closed, the OS kills the app and the timer also stops running.

So we need to save our time somewhere, and then check it, if that saved time has come now.

For that first I created a DateTime instance and saved it on Firestore. You can save that DateTime instance on local Database also, eg:SQFlite etc.

//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));

Now save this instance to FireStore with an ID-

saveTimeToFireStore() async {
await FirebaseFirestore.instance.collection('users').doc('Z0ZuoW8npwuvmBzmF0Wt').set({
  'atFiveInEvening':atFiveInEvening,    
  });
}

Now retrieve this set time from Firestore when the app opens-

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.
  }
}

But here we'll have to run the function getTheTimeToTriggerEvent() again and again to check if the time has come.

You can try Cron

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

Related