add time::Ticker

This commit is contained in:
Dario Nieuwenhuis 2020-12-13 19:54:18 +01:00
parent ca2ff632ba
commit 3be7ace878
2 changed files with 34 additions and 1 deletions

View file

@ -5,7 +5,7 @@ mod traits;
pub use duration::Duration;
pub use instant::Instant;
pub use timer::Timer;
pub use timer::{Ticker, Timer};
pub use traits::*;
use crate::fmt::*;

View file

@ -1,6 +1,7 @@
use core::future::Future;
use core::pin::Pin;
use core::task::{Context, Poll};
use futures::Stream;
use futures_intrusive::timer::{LocalTimer, LocalTimerFuture};
use super::{Duration, Instant};
@ -28,3 +29,35 @@ impl Future for Timer {
unsafe { Pin::new_unchecked(&mut self.get_unchecked_mut().inner) }.poll(cx)
}
}
pub struct Ticker {
inner: LocalTimerFuture<'static>,
next: Instant,
dur: Duration,
}
impl Ticker {
pub fn every(dur: Duration) -> Self {
let next = Instant::now() + dur;
Self {
inner: current_timer_queue().deadline(next.as_ticks()),
next,
dur,
}
}
}
impl Stream for Ticker {
type Item = ();
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let this = unsafe { self.get_unchecked_mut() };
match unsafe { Pin::new_unchecked(&mut this.inner) }.poll(cx) {
Poll::Ready(_) => {
this.next += this.dur;
this.inner = current_timer_queue().deadline(this.next.as_ticks());
Poll::Ready(Some(()))
}
Poll::Pending => Poll::Pending,
}
}
}