Home > other >  run code in background every 10 seconds in flutter
run code in background every 10 seconds in flutter

Time:03-07

I want to run my code in background every 10 seconds.

I use android_alarm_manager_plus package to do this, but the code only runs one time.

void printHello() {
  final DateTime now = DateTime.now();
  final int isolateId = Isolate.current.hashCode;
  print("[$now] Hello, world! isolate=${isolateId} function='$printHello'");
}


void main() async {

  WidgetsFlutterBinding.ensureInitialized();
  await AndroidAlarmManager.initialize();

  runApp(MyApp());

  final int helloAlarmID = 0;
  await AndroidAlarmManager.periodic(const Duration(seconds: 1), helloAlarmID, printHello);
  
}

output:

I/AlarmService(20174): AlarmService started!
W/AlarmService(20174): Attempted to start a duplicate background isolate. Returning...
I/flutter (20174): [2022-03-06 23:07:04.551284] Hello, world! isolate=436793591 function='Closure: () => void from Function 'printHello': static.'

CodePudding user response:

According to an issue of the library, the minimun periodic Duration time is 1 minute, if you put it less than that, by default the library put into 1min.

Android Alarm Manager Plus Periodic Function not working

If you need to manage less, you have to use a method channel.

Also, there is much information: enter link description here

  • Related