Home > other >  Flutter background task every 15 minutes
Flutter background task every 15 minutes

Time:07-21

How to run a simple background task in Flutter every 15 minutes (that will work both in android and Ios) EVEN when app is terminated?

CodePudding user response:

You can use this package

https://pub.dev/packages/workmanager

void callbackDispatcher() {
  Workmanager().executeTask((task, inputData) {
    print("Native called background task: $backgroundTask"); //simpleTask will be emitted here.
    return Future.value(true);
  });
}

void main() {
  Workmanager().initialize(
    callbackDispatcher, // The top level function, aka callbackDispatcher
    isInDebugMode: true // If enabled it will post a notification whenever the task is running. Handy for debugging tasks
  );
Workmanager().registerPeriodicTask(
    "periodic-task-identifier", 
    "simplePeriodicTask", 
    // When no frequency is provided the default 15 minutes is set.
    // Minimum frequency is 15 min. Android will automatically change your frequency to 15 min if you have configured a lower frequency.
    frequency: Duration(minutes: 10),
)
  runApp(MyApp());
}

Create a top level function and you can schedule a work to be done at the backgroun

CodePudding user response:

  Timer? timer;

  taskExecute() {
    print('hello world');
  }

  @override
  void initState() {
      // TODO: implement initState
       super.initState();
       timer = Timer.periodic(Duration(minutes: 15), (Timer t) => taskExecute());
  }

CodePudding user response:

Please add further information about your task and code. I think you are trying to run some particular task repeatedly after 10 minutes. Is that right? If so you can use initState for that to check new data after every 10 minutes. Here is an example code.

@override
  void initState() {
    getStocks();
    Timer.periodic(
      Duration(seconds: 10), // Specify the time to repeat the process
      ((timer) => getStocks()), // Give the function which you want to run repeatedly
    );

    super.initState();
  }
  • Related