How to schedule background tasks in Flutter?

前端 未结 2 1550
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-15 04:23

I have been looking a lot for this but haven\'t found any packages or a way to schedule background tasks in Flutter. Like in Android there is WorkManager,

2条回答
  •  长情又很酷
    2020-12-15 04:44

    SOLUTION 1: android_alarm_manager is the best solution to schedule background tasks. But the only disadvantage is only support Android. Let's start:

    After importing this plugin to your project as usual, add the following to your AndroidManifest.xml within the tags:

    
    
    

    Next, within the tags, add:

    
    
    
        
            
        
    
    

    Then in Dart code add:

    import 'package:android_alarm_manager/android_alarm_manager.dart';
    
    void printHello() {
      final DateTime now = DateTime.now();
      final int isolateId = Isolate.current.hashCode;
      print("[$now] Hello, world! isolate=${isolateId} function='$printHello'");
    }
    
    main() async {
      final int helloAlarmID = 0;
      await AndroidAlarmManager.initialize();
      runApp(...);
      await AndroidAlarmManager.periodic(const Duration(minutes: 1), helloAlarmID, printHello);
    }
    

    If you want to schedule any task every day at a specific time, you need to do something like this:

    if (Platform.isAndroid) {
       await AndroidAlarmManager.periodic(
          const Duration(hours: 24), //Do the same every 24 hours
          helloAlarmID, //Different ID for each alarm
          printHello,
          wakeup: true, //the device will be woken up when the alarm fires
          startAt: DateTime(DateTime.now().year, DateTime.now().month, DateTime.now().day, 5, 0), //Start whit the specific time 5:00 am
          rescheduleOnReboot: true, //Work after reboot
       );
    }
    

    If alarm callbacks will need access to other Flutter plugins, including the alarm manager plugin itself, it may be necessary to inform the background service how to initialize plugins depending on which Flutter Android embedding the application is using.

    This is done by giving the AlarmService a callback to call the application's onCreate method.

    In particular, its Application class is as follows:

    public class Application extends FlutterApplication implements PluginRegistrantCallback {
        @Override
        public void onCreate() {
            super.onCreate();
            AlarmService.setPluginRegistrant(this);
        }
    
        @Override
        public void registerWith(PluginRegistry registry) {
            //add AndroidAlarmManagerPlugin plugin register  if you work with arlarm
            AndroidAlarmManagerPlugin.registerWith(registry.registrarFor("io.flutter.plugins.androidalarmmanager.AndroidAlarmManagerPlugin"));
        }
    }
    

    Which must be reflected in the application's AndroidManifest.xml. E.g.:

    SOLUTION 2: Cron is another best solution to schedule background tasks. Cron run tasks periodically at fixed times, dates or intervals. But the onliy disadvantage of corn is once the app kill, cron not working in background as expected.

    A simple usage example:

    import 'package:cron/cron.dart';
    
    main() {
      var cron = new Cron();
      cron.schedule(new Schedule.parse('*/3 * * * *'), () async {
        print('every three minutes');
      });
      cron.schedule(new Schedule.parse('8-11 * * * *'), () async {
        print('between every 8 and 11 minutes');
      });
    }
    

    How to setup a cronjob in general: information

    Test cronjob: crontab

提交回复
热议问题