Hi,
Im new to rust and would like to know how to mutate a global variable using tokio/futures.
[dependencies]
tokio = { version = "0.3.0", features = ["rt", "rt-multi-thread", "macros", "time"] }
use tokio::time::{self, Duration};
use std::future::Future;
#[tokio::main]
async fn main() {
let mut mutate = 0; // how do i increment this inside the interval ?
set_interval(|| async {
mutate = mutate + 1;
println!("{}", mutate);
}, 5000);
time::sleep(Duration::from_millis(60000)).await;
}
fn set_interval<F, Fut>(mut task: F, dur: u64)
where
F: Send + 'static + FnMut() -> Fut,
Fut: Future<Output = ()> + Send + 'static,
{
let mut interval = time::interval(Duration::from_millis(dur));
tokio::spawn(async move {
// Skip the first tick at 0ms.
interval.tick().await;
loop {
interval.tick().await;
tokio::spawn(task());
}
});
}