Search code examples
multithreadingrustwebsocketrust-actix

How to create individual thread for sending pings on client webscoket


I wrote this code, but when sending pings, the program cannot do anything else. How can I spawn another thread to do this work while I do something else in my program?

 pub fn sending_ping(addr: Addr<MicroscopeClient>) -> Result<(), ()> {
    info!("Pings started");

    spawn(async move {
        loop {
            info!("Ping");
            match addr.send(Ping {}).await {
                Ok(_) => {
                    info!("Ping sended")
                }
                Err(e) => {
                    warn!("Ping error");
                    return;
                }
            }
            std::thread::sleep(Duration::from_millis((4000) as u64));
        }
    });
    return Ok(());
}

Solution

  • I solved this particular problem in the following way

    fn send_heartbeat(&self, ctx: &mut <Self as Actor>::Context) {
        ctx.run_interval(HEARTBEAT_INTERVAL, |act, ctx| {
            if Instant::now().duration_since(act.hb) > CLIENT_TIMEOUT {
                info!("Websocket Client heartbeat failed, disconnecting!");
                act.server_addr.do_send(Disconnect {
                    id: act.user_id.clone(),
                });
                ctx.stop();
    
                return;
            }
        });
    }
    

    But I still don't know how to start some long process in a websocket in a separate thread, so that it does not block the websocket, with tokio="0.2.0" and actix="0.3.0".