futures_time/stream/
interval.rs1use std::future::Future;
2use std::pin::Pin;
3use std::task::{Context, Poll};
4
5use async_io::Timer;
6use futures_core::stream::Stream;
7
8use crate::time::{Duration, Instant};
9
10pub fn interval(dur: Duration) -> Interval {
23 Interval {
24 timer: Timer::after(dur.into()),
25 interval: dur,
26 }
27}
28
29#[must_use = "streams do nothing unless polled or .awaited"]
36#[derive(Debug)]
37pub struct Interval {
38 timer: Timer,
39 interval: Duration,
40}
41
42impl Stream for Interval {
43 type Item = Instant;
44
45 fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
46 let instant = match Pin::new(&mut self.timer).poll(cx) {
47 Poll::Ready(instant) => instant,
48 Poll::Pending => return Poll::Pending,
49 };
50 let interval = self.interval;
51 let _ = std::mem::replace(&mut self.timer, Timer::after(interval.into()));
52 Poll::Ready(Some(instant.into()))
53 }
54}