use std::time::{Duration, Instant};
use async_std::io::{self};
use async_std::prelude::*;
use async_std::stream;
use async_std::task;
fn main() -> io::Result<()> {
task::block_on(async {
let mut interval_1 = stream::interval(Duration::from_secs(2));
while let Some(_) = interval_1.next().await {
println!("123");
}
let mut interval_2 = stream::interval(Duration::from_secs(1));
while let Some(_) = interval_2.next().await {
println!("456");
}
Ok(())
})
}
Not sure if I'm following correctly but I'm not getting 456 printed.
How should I change that to make it work?
Regards
@cole-acepph
stream::interval function is return endless stream, so first while loop repeats indefinintly.
Thus second while loop is not worked.
This code should work what you expected.
Two loop can work simultaneously by spawning two threads.
use async_std::io;
use async_std::prelude::*;
use async_std::stream;
use async_std::task;
use std::time::Duration;
fn main() -> io::Result<()> {
task::block_on(async {
// Spawn a new thread
let a = task::spawn(async {
let mut interval_1 = stream::interval(Duration::from_secs(2));
while let Some(_) = interval_1.next().await {
println!("123");
}
});
// Spawn a new thread
let b = task::spawn(async {
let mut interval_2 = stream::interval(Duration::from_secs(1));
while let Some(_) = interval_2.next().await {
println!("456");
}
});
// Waits for two futures to complete.
a.join(b).await;
Ok(())
})
}
I hope this will help you 😄
nice, yeah that's what I was exactly needing, another question I have is, the first thread will generate data that the 2nd thread would need, what's the best way to handle that? i.e. the first thread will create objects based on some input and the second one would have to save that data in a DB, what would be the best data bus for it?
Regards
Does using a channel solve that ❓
https://doc.rust-lang.org/book/ch16-02-message-passing.html
https://docs.rs/async-std/1.4.0/async_std/sync/fn.channel.html
thanks! I'll take a look
Close as it looks like it has been resolved.