How to call a closure with a delay in Rust? Is tokio::timer::Delay
a proper tool for making asynchronous callbacks?
My code:
pub struct Object1 {
k1: i32,
}
//
impl Object1 {
pub fn new() -> Object1 {
Object1 { k1: 13 }
}
}
//
fn main() {
let object1: Box<Object1> = Box::new(Object1::new());
callback_call_1(Box::new(|| {
println!("{:?}", object1.k1);
}));
}
//
fn callback_call_1<F>(mut callback1: F)
where
F: FnMut(),
{
println!("inside callback_call_1");
callback1();
/* how to call callback1 with delay 1 second, not blocking the thread?
is it possible to call the callback1 in the same thread?
is it possible to reach similar behavior setTimeout from JavaScript has?
*/
}
Here is playground .
Here's how to do it with latest Tokio:
tokio::time::sleep(duration).await;
callback1().await;
To call it repeatedly on an interval, use a loop:
let mut interval = tokio::time::interval(duration);
loop {
interval.tick().await;
callback1().await;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.