skip to Main Content

I am starting a CRON service, to fetch a list of events from Firebase, in flutter main().

My question is: where to cancel the CRON service when the app closes?

void main() async {
await Firebase.initializeApp();
final cron = Cron();
final EventFirebaseServices _eventFirebaseServices = EventFirebaseServices();
cron.schedule(Schedule.parse('0 * * * *), (async {
await _eventFirebaseServices.getEventList();
});
}

Is there a "Dispose" method for main?

Thanks,

Pierre

2

Answers


  1. If you are instanciating your cron class within the main method you can’t dispose it becauze there is no widget lifecycle with a dispose method inside the main function. One solution is to make a global class of the cron class or make a global provider of that cron class, by doing this you can access your cron class inside a widget and clean up the resources of the cron when the app is terminated. Inside your main widget of your application ( the main widget inside the MaterialApp widget ) you can extend the WidgetBindingObserver which allow you to listen when the apps i paused resumed or terminated. Here since you have this possibility you can access your global cron class or provider of that class and clean up the resources.

    class MainWidget extends WidgetsBindingObserver {
      
      MainWidget();
      @override
      void didChangeAppLifecycleState(AppLifecycleState state) {
        if (state == AppLifecycleState.terminated) {
          cron.cancel(); // Cancel or stop the cron tasks when the app is terminated
        }
      }
    }
    

    To make a global class you can instanciate your cron class outside of the main method by calling Cron cron = Cron(); In order instead to create a provider i suggest you to start learning this topic to give to your code a well managed structure.

    Login or Signup to reply.
  2. You don’t need to cancel it because it will not run if the app is closed. In fact, there is no guarantee that it will run even if your app is in the background. This package was designed for server apps, not mobile apps, if you check the source code it just uses Timer.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search