Tipu Sultan
Tipu Sultan

Reputation: 1865

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

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

Upvotes: 7

Views: 8909

Answers (4)

Rahul Kushwaha
Rahul Kushwaha

Reputation: 6722

You can use like this:-

Define DateTime and StreamSubscription. .

var setTime = DateTime.utc(2023, 3, 29, 14, 59, 0).toLocal();
StreamSubscription? subscription;

Set the stream for Periodic run/trigger .

 var stream = Stream.periodic(const Duration(days: 1), (count) {
     return DateTime.now().isAfter(setTime);
});

Now ,listen to your stream as follows.

subscription = stream.listen((result) {
    print('running');
    subscription!.cancel();
    print(result);
  });

Upvotes: 0

Jeff
Jeff

Reputation: 475

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

Upvotes: 3

Madhav Kumar
Madhav Kumar

Reputation: 1114

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.

Upvotes: 2

JerryZhou
JerryZhou

Reputation: 5166

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

Upvotes: 8

Related Questions