Skip to content

Instantly share code, notes, and snippets.

@mcbridejc
Created February 12, 2020 22:52
Show Gist options
  • Save mcbridejc/eb11d43e9440431184b614d7293aa4f7 to your computer and use it in GitHub Desktop.
Save mcbridejc/eb11d43e9440431184b614d7293aa4f7 to your computer and use it in GitHub Desktop.
Tokio multiple periodic actions with Interval
[package]
name = "multidelaytest"
version = "0.1.0"
authors = ["Jeff McBride"]
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
tokio = { version = "0.2", features = ["macros", "time", "sync", "rt-core", "rt-threaded", "rt-util", "stream"] }
futures = "0.3"
use futures::future;
use std::time::Duration;
use std::thread;
async fn start(frequencies: Vec<f32>) {
tokio::spawn(async move {
let mut streams = Vec::new();
for f in frequencies {
streams.push(tokio::time::interval(Duration::from_secs_f32(1.0 / f)));
}
loop {
let futures = streams.iter_mut().map(|s| {Box::pin(s.tick())});
let (_res, idx, _remaining_futures) = future::select_all(futures).await;
println!("Got sensor {:?}", idx);
}
}).await.unwrap()
}
#[tokio::main]
async fn main() {
println!("Launching background timers");
start(vec![0.5, 1.0, 2.0]).await;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment