Files
tokio/src/reactor/timeout_token.rs
T

79 lines
2.3 KiB
Rust
Raw Normal View History

2016-08-20 23:23:16 -07:00
use std::io;
use std::time::Instant;
use futures::{Future, Poll};
use futures::task;
2016-09-02 11:07:52 -07:00
use reactor::{Message, Core, Handle, CoreFuture};
2016-08-20 23:23:16 -07:00
2016-09-02 11:07:52 -07:00
/// Return value from the `Handle::add_timeout` method, a future that will
/// resolve to a `TimeoutToken` to configure the behavior of that timeout.
pub struct TimeoutTokenNew {
inner: CoreFuture<(usize, Instant), Instant>,
}
/// A token that identifies an active timeout.
pub struct TimeoutToken {
token: usize,
when: Instant,
}
impl TimeoutToken {
2016-08-20 23:23:16 -07:00
/// Adds a new timeout to get fired at the specified instant, notifying the
/// specified task.
2016-09-02 11:07:52 -07:00
pub fn new(at: Instant, handle: &Handle) -> TimeoutTokenNew {
TimeoutTokenNew {
inner: CoreFuture {
handle: handle.clone(),
2016-08-20 23:23:16 -07:00
data: Some(at),
result: None,
},
}
}
2016-09-02 11:07:52 -07:00
/// Returns the instant in time when this timeout token will "fire".
///
/// Note that this instant may *not* be the instant that was passed in when
/// the timeout was created. The event loop does not support high resolution
/// timers, so the exact resolution of when a timeout may fire may be
/// slightly fudged.
pub fn when(&self) -> &Instant {
&self.when
}
2016-08-20 23:23:16 -07:00
/// Updates a previously added timeout to notify a new task instead.
///
/// # Panics
///
/// This method will panic if the timeout specified was not created by this
/// loop handle's `add_timeout` method.
2016-09-02 11:07:52 -07:00
pub fn update_timeout(&self, handle: &Handle) {
handle.send(Message::UpdateTimeout(self.token, task::park()))
2016-08-20 23:23:16 -07:00
}
/// Cancel a previously added timeout.
///
/// # Panics
///
/// This method will panic if the timeout specified was not created by this
/// loop handle's `add_timeout` method.
2016-09-02 11:07:52 -07:00
pub fn cancel_timeout(&self, handle: &Handle) {
debug!("cancel timeout {}", self.token);
handle.send(Message::CancelTimeout(self.token))
2016-08-20 23:23:16 -07:00
}
}
2016-09-02 11:07:52 -07:00
impl Future for TimeoutTokenNew {
2016-08-20 23:23:16 -07:00
type Item = TimeoutToken;
type Error = io::Error;
fn poll(&mut self) -> Poll<TimeoutToken, io::Error> {
2016-09-02 11:07:52 -07:00
let (t, i) = try_ready!(self.inner.poll(Core::add_timeout,
Message::AddTimeout));
2016-09-01 16:42:48 -07:00
Ok(TimeoutToken {
token: t,
when: i,
}.into())
2016-08-20 23:23:16 -07:00
}
}