emilk / ehttp

Minimal Rust HTTP client for both native and WASM
Apache License 2.0
323 stars 30 forks source link

Make sequence request to a device in an interval time with egui + ehttp? #26

Closed anbkhn closed 1 year ago

anbkhn commented 1 year ago

Hi ,

I am developing a tool that read info from a device via http and I am using egui + ehttp for this problem. For this device, I need to make 2 requests to get the last content I want

First, I need to make a request to: "http://192.168.0.11/abcxyz" then the device will return a result that contains a temp link inside. I will use regex to get the temp link then make the second request to device: "http://192.168.0.11/templink" The result will return the info I need.

The problem is: I want to make the full request (first and second request) after an interval time, let says: 1 minutes. Could you give me an advice of doing this?

emilk commented 1 year ago

To make it portable between web and native you need to do something like this:

#[cfg(not(target_arch = "wasm32"))]
fn call_after_delay(delay: std::time::Duration, f: impl FnOnce() + Send + 'static) {
    std::thread::spawn(move || {
        std::thread::sleep(delay);
        f();
    });
}

#[cfg(target_arch = "wasm32")]
fn call_after_delay(delay: std::time::Duration, f: impl FnOnce() + Send + 'static) {
    use wasm_bindgen::prelude::*;
    let window = web_sys::window().unwrap();
    let closure = Closure::once(f);
    let delay_ms = delay.as_millis() as _;
    window
        .set_timeout_with_callback_and_timeout_and_arguments_0(
            closure.as_ref().unchecked_ref(),
            delay_ms,
        )
        .unwrap();
    closure.forget(); // We must forget it, or else the callback is canceled on drop
}