Files
tokio/tokio-timer/src/interval.rs
T

73 lines
2.1 KiB
Rust
Raw Normal View History

2019-05-14 10:27:36 -07:00
use crate::clock;
use crate::Delay;
use futures::{try_ready, Future, Poll, Stream};
2019-02-21 11:56:15 -08:00
use std::time::{Duration, Instant};
2018-03-28 22:26:47 -07:00
/// A stream representing notifications at fixed interval
#[derive(Debug)]
pub struct Interval {
/// Future that completes the next time the `Interval` yields a value.
2018-03-30 14:21:48 -07:00
delay: Delay,
2018-03-28 22:26:47 -07:00
/// The duration between values yielded by `Interval`.
duration: Duration,
}
impl Interval {
/// Create a new `Interval` that starts at `at` and yields every `duration`
/// interval after that.
///
/// Note that when it starts, it produces item too.
///
2018-03-28 22:26:47 -07:00
/// The `duration` argument must be a non-zero duration.
///
/// # Panics
///
/// This function panics if `duration` is zero.
pub fn new(at: Instant, duration: Duration) -> Interval {
2019-02-21 11:56:15 -08:00
assert!(
duration > Duration::new(0, 0),
"`duration` must be non-zero."
);
2018-03-28 22:26:47 -07:00
2018-03-30 14:21:48 -07:00
Interval::new_with_delay(Delay::new(at), duration)
2018-03-28 22:26:47 -07:00
}
/// Creates new `Interval` that yields with interval of `duration`.
///
/// The function is shortcut for `Interval::new(Instant::now() + duration, duration)`.
///
/// The `duration` argument must be a non-zero duration.
///
/// # Panics
///
/// This function panics if `duration` is zero.
pub fn new_interval(duration: Duration) -> Interval {
Interval::new(clock::now() + duration, duration)
}
2018-03-30 14:21:48 -07:00
pub(crate) fn new_with_delay(delay: Delay, duration: Duration) -> Interval {
2019-02-21 11:56:15 -08:00
Interval { delay, duration }
2018-03-28 22:26:47 -07:00
}
}
impl Stream for Interval {
type Item = Instant;
2019-05-14 10:27:36 -07:00
type Error = crate::Error;
2018-03-28 22:26:47 -07:00
fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> {
2018-03-30 14:21:48 -07:00
// Wait for the delay to be done
let _ = try_ready!(self.delay.poll());
2018-03-28 22:26:47 -07:00
2018-03-30 14:21:48 -07:00
// Get the `now` by looking at the `delay` deadline
let now = self.delay.deadline();
2018-03-28 22:26:47 -07:00
// The next interval value is `duration` after the one that just
// yielded.
2018-03-30 14:21:48 -07:00
self.delay.reset(now + self.duration);
2018-03-28 22:26:47 -07:00
// Return the current instant
Ok(Some(now).into())
}
}