1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
use std::time::Instant; use super::conf::Conf; use super::listen_utils::*; use crate::server::swap_cmd::SwapCmd; use std::net::SocketAddr; use async_trait::async_trait; pub struct Timer { time: Instant, } impl Timer { pub fn start() -> Self { Timer { time: Instant::now(), } } } #[async_trait] pub trait HeartBeat { async fn heart_beat(&mut self) -> anyhow::Result<()>; } #[async_trait] impl HeartBeat for Timer { async fn heart_beat(&mut self) -> anyhow::Result<()> { let conf = Conf::get(); let id = conf.id; if id == "".to_string() { return Ok(()); } let elapse = self.time.elapsed().as_secs() as i32; if elapse < conf.heart_beat_interval { return Ok(()); } self.time = Instant::now(); let hb = SwapCmd::save(&id); let s = &conf.swap_server; let address: SocketAddr = s.parse()?; let soc = SOC.get().unwrap(); soc.send_to(&hb, address).await?; Ok(()) } }