问题
我已经实现了一个函数,它从发送的数据包中返回一组缺失的索引。如果发送了 100 个数据包,那么服务器将有一个索引向量,索引为 0(缺失)和 1(未缺失)。我不想每次都触发这个,只有在没有收到数据包的情况下有轻微的延迟。我想将我的同步函数更改为异步去抖动函数
我尝试解决去抖动问题
我正在寻找一种解决方案来实现一个计时器(如 300 毫秒),它的值将不断被不同的线程覆盖。一旦它的值不再被覆盖,它应该触发一段代码或函数。我正在使用东京。
这是我想要实现的伪代码:
// thanks https://stackoverflow.com/questions/26593387/how-can-i-get-the-current-time-in-milliseconds
fn get_epoch() -> u128 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_millis()
}
impl Server {
async fn run(self) -> Result<(), io::Error> {
let Server {
socket,
mut buf,
mut to_send,
} = self;
let mut timer_delay = get_epoch();
loop {
if let Some((size, peer)) = to_send {
timer_delay = get_epoch(); // "reset" the to a closer value
}
futures::join!(
/* execute a block of code if true*/
if get_epoch() - timer_delay > 300,
/* else (default case):*/
to_send = Some(socket.recv_from(&mut buf)
);
}
}
}
我的项目基于Tokio的以下示例:
impl Server {
async fn run(self) -> Result<(), io::Error> {
let Server {
socket,
mut buf,
mut to_send,
} = self;
loop {
// First we check to see if there's a message we need to echo back.
// If so then we try to send it back to the original source, waiting
// until it's writable and we're able to do so.
if let Some((size, peer)) = to_send {
let amt = socket.send_to(&buf[..size], &peer).await?;
println!("Echoed {}/{} bytes to {}", amt, size, peer);
}
// If we're here then `to_send` is `None`, so we take a look for the
// next message we're going to echo back.
to_send = Some(socket.recv_from(&mut buf).await?);
}
}
}