Marc Paul
Marc Paul

Reputation: 37

How to have delay after every Timer.periodic

I am using the Timer.periodic code below for every X seconds to send a message to another device using my customized _sendmessage function to make sure that there is still connection.

@override
    void initState() {
      super.initState();
      timer = Timer.periodic(Duration(seconds: 5), (Timer t) => 
        _sendmessage('Alive'));
    }
    
    @override
    void dispose() {
      timer?.cancel();
      super.dispose();
    }

My problem is I also use _sendmessage on sending other data to another device such as when a button is pressed. Therefore there is a chance that the button is pressed and Timer.periodic can happen at the same time or right after one another causing loosing data received by another device (this another device can only read 1 string at a time).

How to have delay after every Timer.periodic to make sure the above case will not happen?

Upvotes: 0

Views: 71

Answers (1)

Nguyen family
Nguyen family

Reputation: 1048

I suggest you use a variable called "isSendingData". Whenever you call _sendmessage, update it to true and after finish, update it to false.

If your button is pressed, you can check if isSendingData == true and don't trigger action _sendmessage again.

But I think the problem is in your another device - there may be something wrong when it receives data. Hope you will find someways to make it possible to receives second data right after the first one.

Upvotes: 0

Related Questions