Search code examples
rustiterationtimeoutrumqttc

Timeout on blocking iteration?


I have the following working code:

// send it via mqtt
use rumqttc::{MqttOptions, Client, QoS};

let mut mqttoptions = MqttOptions::new("rumqtt-sync", "mqtt.example.com", 1883);
mqttoptions.set_keep_alive(Duration::from_secs(5));

let (mut client, mut connection) = Client::new(mqttoptions, 10);
let _ = client.publish("foo/bar", QoS::AtLeastOnce, false, json);

// iterate to poll the eventloop for connection progress
for (i, notification) in connection.iter().enumerate() {
    println!("Notification = {:?}", notification);
}

When I use channels, I can listen with a timeout using mpsc::recv_timeout.

How can check for notifications for a short period of time (e.g. 3 seconds) before continuing with the program if nothing is received?


Solution

  • Luckily for you, rumqttc provides recv_timeout():

    let timeout = ...;
    let mut i = 0;
    loop {
        do_something_if_nothing_received();
        let Ok(notification) = connection.recv_timeout(timeout) else {
            continue;
        };
        let Ok(notification) = notification else {
            break;
        }
        i += 1;
        println!("Notification = {:?}", notification);
    }
    

    But in general, as @cdhowie said, if this functionality is not provided by the system, you cannot have it in blocking APIs.