Async-std: Trying to run more than one interval

Created on 13 Jan 2020  ·  5Comments  ·  Source: async-rs/async-std

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

questiofeedback

All 5 comments

@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

thanks! I'll take a look

Close as it looks like it has been resolved.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Nokel81 picture Nokel81  ·  3Comments

yoshuawuyts picture yoshuawuyts  ·  6Comments

humb1t picture humb1t  ·  5Comments

yoshuawuyts picture yoshuawuyts  ·  5Comments

Darksonn picture Darksonn  ·  7Comments