tokio_core/reactor/interval.rs
1//! Support for creating futures that represent intervals.
2//!
3//! This module contains the `Interval` type which is a stream that will
4//! resolve at a fixed intervals in future
5
6use std::io;
7use std::time::{Duration, Instant};
8
9use futures::Poll;
10use futures::Stream;
11use tokio_timer::Interval as NewInterval;
12
13use reactor::Handle;
14
15/// A stream representing notifications at fixed interval
16///
17/// Intervals are created through the `Interval::new` or
18/// `Interval::new_at` methods indicating when a first notification
19/// should be triggered and when it will be repeated.
20///
21/// Note that timeouts are not intended for high resolution timers, but rather
22/// they will likely fire some granularity after the exact instant that they're
23/// otherwise indicated to fire at.
24#[must_use = "streams do nothing unless polled"]
25pub struct Interval {
26 new: NewInterval
27}
28
29impl Interval {
30 /// Creates a new interval which will fire at `dur` time into the future,
31 /// and will repeat every `dur` interval after
32 ///
33 /// This function will return a future that will resolve to the actual
34 /// interval object. The interval object itself is then a stream which will
35 /// be set to fire at the specified intervals
36 pub fn new(dur: Duration, handle: &Handle) -> io::Result<Interval> {
37 Interval::new_at(Instant::now() + dur, dur, handle)
38 }
39
40 /// Creates a new interval which will fire at the time specified by `at`,
41 /// and then will repeat every `dur` interval after
42 ///
43 /// This function will return a future that will resolve to the actual
44 /// timeout object. The timeout object itself is then a future which will be
45 /// set to fire at the specified point in the future.
46 pub fn new_at(at: Instant, dur: Duration, handle: &Handle)
47 -> io::Result<Interval>
48 {
49 Ok(Interval {
50 new: handle.remote.timer_handle.interval(at, dur)
51 })
52 }
53}
54
55impl Stream for Interval {
56 type Item = ();
57 type Error = io::Error;
58
59 fn poll(&mut self) -> Poll<Option<()>, io::Error> {
60 self.new.poll()
61 .map(|async| async.map(|option| option.map(|_| ())))
62 .map_err(|err| io::Error::new(io::ErrorKind::Other, err))
63 }
64}