Is there a way for Flutter's Timer.periodic to wait for a function return plus a fixed duration before moving to the next cycle?

3,676

Solution 1

void startTimer() {
  _timer = Timer.periodic(Duration(seconds: 1), (Timer t) async {
  print("lets wait for 5 seconds");
  _timer.cancel();
  await Future.delayed(Duration(seconds: 5));
  print("Job is done");
  print(DateTime.now());
  print("Do it again");
  startTimer();
});

}

Solution 2

I have encountered the same situation lately, what I did was (in my case inside a static class) to add a static boolean value and toggle it accoding to my situation needs, later checking it's value inside the Timer.Periodic callback.

Timer.periodic(ConstantValues.socketTimerOperationDelay, (Timer t) async{
      if(_udpHandlerCompleted){
        _udpHandlerCompleted = false;
        if(!_shouldSendBroadcast || _shutDown)
          t.cancel();
        else
          _writeAllToUdpSocket(_udpSocket, data, ConstantValues.udpMulticastGroup, ConstantValues.udpMulticastPort);
        _udpHandlerCompleted = true;
      }
    });

As you can see in my situation, I had to wait for the callback to end before I move to the next one, I believe this is what you're looking for, but in case you need to await for a different method the solution would be similar, simply toggle the boolean _udpHandlerCompleted (in my case) in the other function.

Edit: If my soultion helped you, kindly mark it as the accepted answer. Good luck!

Share:
3,676
Richard
Author by

Richard

Updated on December 16, 2022

Comments

  • Richard
    Richard over 1 year

    I use Timer.periodic with a duration normally. This works perfectly for my current use case.

    Duration fiveSecs = const Duration(seconds: 5);
    new Timer.periodic(fiveSecs, checkChange);
    
    void checkChange(Timer timer) async {
       //do some network calls
    }
    

    In this particular case I make network calls that take no longer than 500ms, and doing them every 5 seconds is enough for whatever depends on what those calls return.

    Now I want to check for new values as frequently as 2 seconds, however, based on what needs to be checked a network call could take anywhere from a few hundred milliseconds to even 10 seconds. I could give a large margin and use a frequency of like 20 seconds for the timer, but in this case I would even prefer a 1 second frequency if possible.

    So is there a way the timer could wait for a function, and still have a fixed duration like 1 second. So the maximum time it would take would be 1 second + callback runtime? Or is there a better way this could be achieved, I'm open to suggestions. Thank you.

    • pskink
      pskink over 4 years
      use multiple Timers one after another, not Timer.periodic