[][src]Struct tokio_timer::DelayQueue

pub struct DelayQueue<T> { /* fields omitted */ }

A queue of delayed elements.

Once an element is inserted into the DelayQueue, it is yielded once the specified deadline has been reached.

Usage

Elements are inserted into DelayQueue using the insert or insert_at methods. A deadline is provided with the item and a Key is returned. The key is used to remove the entry or to change the deadline at which it should be yielded back.

Once delays have been configured, the DelayQueue is used via its Stream implementation. poll is called. If an entry has reached its deadline, it is returned. If not, Async::NotReady indicating that the current task will be notified once the deadline has been reached.

Stream implementation

Items are retrieved from the queue via Stream::poll. If no delays have expired, no items are returned. In this case, NotReady is returned and the current task is registered to be notified once the next item's delay has expired.

If no items are in the queue, i.e. is_empty() returns true, then poll returns Ready(None). This indicates that the stream has reached an end. However, if a new item is inserted after, poll will once again start returning items or `NotReady.

Items are returned ordered by their expirations. Items that are configured to expire first will be returned first. There are no ordering guarantees for items configured to expire the same instant. Also note that delays are rounded to the closest millisecond.

Implementation

The DelayQueue is backed by the same hashed timing wheel implementation as Timer as such, it offers the same performance benefits. See Timer for further implementation notes.

State associated with each entry is stored in a slab. This allows amortizing the cost of allocation. Space created for expired entries is reused when inserting new entries.

Capacity can be checked using capacity and allocated preemptively by using the reserve method.

Usage

Using DelayQueue to manage cache entries.

use tokio::timer::{delay_queue, DelayQueue, Error};

use futures_core::ready;
use std::collections::HashMap;
use std::task::{Context, Poll};
use std::time::Duration;

struct Cache {
    entries: HashMap<CacheKey, (Value, delay_queue::Key)>,
    expirations: DelayQueue<CacheKey>,
}

const TTL_SECS: u64 = 30;

impl Cache {
    fn insert(&mut self, key: CacheKey, value: Value) {
        let delay = self.expirations
            .insert(key.clone(), Duration::from_secs(TTL_SECS));

        self.entries.insert(key, (value, delay));
    }

    fn get(&self, key: &CacheKey) -> Option<&Value> {
        self.entries.get(key)
            .map(|&(ref v, _)| v)
    }

    fn remove(&mut self, key: &CacheKey) {
        if let Some((_, cache_key)) = self.entries.remove(key) {
            self.expirations.remove(&cache_key);
        }
    }

    fn poll_purge(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Error>> {
        while let Some(res) = ready!(self.expirations.poll_next(cx)) {
            let entry = res?;
            self.entries.remove(entry.get_ref());
        }

        Poll::Ready(Ok(()))
    }
}

Methods

impl<T> DelayQueue<T>[src]

pub fn new() -> DelayQueue<T>[src]

Create a new, empty, DelayQueue

The queue will not allocate storage until items are inserted into it.

Examples

let delay_queue: DelayQueue<u32> = DelayQueue::new();

pub fn with_capacity_and_handle(
    capacity: usize,
    handle: &Handle
) -> DelayQueue<T>
[src]

Create a new, empty, DelayQueue backed by the specified timer.

The queue will not allocate storage until items are inserted into it.

Examples

use tokio_timer::timer::Handle;

let handle = Handle::default();
let delay_queue: DelayQueue<u32> = DelayQueue::with_capacity_and_handle(0, &handle);

pub fn with_capacity(capacity: usize) -> DelayQueue<T>[src]

Create a new, empty, DelayQueue with the specified capacity.

The queue will be able to hold at least capacity elements without reallocating. If capacity is 0, the queue will not allocate for storage.

Examples

let mut delay_queue = DelayQueue::with_capacity(10);

// These insertions are done without further allocation
for i in 0..10 {
    delay_queue.insert(i, Duration::from_secs(i));
}

// This will make the queue allocate additional storage
delay_queue.insert(11, Duration::from_secs(11));

pub fn insert_at(&mut self, value: T, when: Instant) -> Key[src]

Insert value into the queue set to expire at a specific instant in time.

This function is identical to insert, but takes an Instant instead of a Duration.

value is stored in the queue until when is reached. At which point, value will be returned from poll. If when has already been reached, then value is immediately made available to poll.

The return value represents the insertion and is used at an argument to remove and reset. Note that Key is token and is reused once value is removed from the queue either by calling poll after when is reached or by calling remove. At this point, the caller must take care to not use the returned Key again as it may reference a different item in the queue.

See type level documentation for more details.

Panics

This function panics if when is too far in the future.

Examples

Basic usage

use tokio::timer::DelayQueue;
use std::time::{Instant, Duration};

let mut delay_queue = DelayQueue::new();
let key = delay_queue.insert_at(
    "foo", Instant::now() + Duration::from_secs(5));

// Remove the entry
let item = delay_queue.remove(&key);
assert_eq!(*item.get_ref(), "foo");

pub fn poll_next(
    &mut self,
    cx: &mut Context
) -> Poll<Option<Result<Expired<T>, Error>>>
[src]

Attempt to pull out the next value of the delay queue, registering the current task for wakeup if the value is not yet available, and returning None if the queue is exhausted.

pub fn insert(&mut self, value: T, timeout: Duration) -> Key[src]

Insert value into the queue set to expire after the requested duration elapses.

This function is identical to insert_at, but takes a Duration instead of an Instant.

value is stored in the queue until when is reached. At which point, value will be returned from poll. If when has already been reached, then value is immediately made available to poll.

The return value represents the insertion and is used at an argument to remove and reset. Note that Key is token and is reused once value is removed from the queue either by calling poll after when is reached or by calling remove. At this point, the caller must take care to not use the returned Key again as it may reference a different item in the queue.

See type level documentation for more details.

Panics

This function panics if timeout is greater than the maximum supported duration.

Examples

Basic usage

use tokio::timer::DelayQueue;
use std::time::Duration;

let mut delay_queue = DelayQueue::new();
let key = delay_queue.insert("foo", Duration::from_secs(5));

// Remove the entry
let item = delay_queue.remove(&key);
assert_eq!(*item.get_ref(), "foo");

pub fn remove(&mut self, key: &Key) -> Expired<T>[src]

Remove the item associated with key from the queue.

There must be an item associated with key. The function returns the removed item as well as the Instant at which it will the delay will have expired.

Panics

The function panics if key is not contained by the queue.

Examples

Basic usage

use tokio::timer::DelayQueue;
use std::time::Duration;

let mut delay_queue = DelayQueue::new();
let key = delay_queue.insert("foo", Duration::from_secs(5));

// Remove the entry
let item = delay_queue.remove(&key);
assert_eq!(*item.get_ref(), "foo");

pub fn reset_at(&mut self, key: &Key, when: Instant)[src]

Sets the delay of the item associated with key to expire at when.

This function is identical to reset but takes an Instant instead of a Duration.

The item remains in the queue but the delay is set to expire at when. If when is in the past, then the item is immediately made available to the caller.

Panics

This function panics if when is too far in the future or if key is not contained by the queue.

Examples

Basic usage

use tokio::timer::DelayQueue;
use std::time::{Duration, Instant};

let mut delay_queue = DelayQueue::new();
let key = delay_queue.insert("foo", Duration::from_secs(5));

// "foo" is scheduled to be returned in 5 seconds

delay_queue.reset_at(&key, Instant::now() + Duration::from_secs(10));

// "foo"is now scheduled to be returned in 10 seconds

pub fn reset(&mut self, key: &Key, timeout: Duration)[src]

Sets the delay of the item associated with key to expire after timeout.

This function is identical to reset_at but takes a Duration instead of an Instant.

The item remains in the queue but the delay is set to expire after timeout. If timeout is zero, then the item is immediately made available to the caller.

Panics

This function panics if timeout is greater than the maximum supported duration or if key is not contained by the queue.

Examples

Basic usage

use tokio::timer::DelayQueue;
use std::time::Duration;

let mut delay_queue = DelayQueue::new();
let key = delay_queue.insert("foo", Duration::from_secs(5));

// "foo" is scheduled to be returned in 5 seconds

delay_queue.reset(&key, Duration::from_secs(10));

// "foo"is now scheduled to be returned in 10 seconds

pub fn clear(&mut self)[src]

Clears the queue, removing all items.

After calling clear, poll will return Ok(Ready(None)).

Note that this method has no effect on the allocated capacity.

Examples

use tokio::timer::DelayQueue;
use std::time::Duration;

let mut delay_queue = DelayQueue::new();

delay_queue.insert("foo", Duration::from_secs(5));

assert!(!delay_queue.is_empty());

delay_queue.clear();

assert!(delay_queue.is_empty());

pub fn capacity(&self) -> usize[src]

Returns the number of elements the queue can hold without reallocating.

Examples

use tokio_timer::DelayQueue;

let delay_queue: DelayQueue<i32> = DelayQueue::with_capacity(10);
assert_eq!(delay_queue.capacity(), 10);

pub fn reserve(&mut self, additional: usize)[src]

Reserve capacity for at least additional more items to be queued without allocating.

reserve does nothing if the queue already has sufficient capacity for additional more values. If more capacity is required, a new segment of memory will be allocated and all existing values will be copied into it. As such, if the queue is already very large, a call to reserve can end up being expensive.

The queue may reserve more than additional extra space in order to avoid frequent reallocations.

Panics

Panics if the new capacity exceeds the maximum number of entries the queue can contain.

Examples

use tokio_timer::DelayQueue;
use std::time::Duration;

let mut delay_queue = DelayQueue::new();

delay_queue.insert("hello", Duration::from_secs(10));
delay_queue.reserve(10);

assert!(delay_queue.capacity() >= 11);

pub fn is_empty(&self) -> bool[src]

Returns true if there are no items in the queue.

Note that this function returns false even if all items have not yet expired and a call to poll will return NotReady.

Examples

use tokio_timer::DelayQueue;
use std::time::Duration;

let mut delay_queue = DelayQueue::new();
assert!(delay_queue.is_empty());

delay_queue.insert("hello", Duration::from_secs(5));
assert!(!delay_queue.is_empty());

Trait Implementations

impl<T> Unpin for DelayQueue<T>[src]

impl<T> Default for DelayQueue<T>[src]

impl<T: Debug> Debug for DelayQueue<T>[src]

impl<T> Stream for DelayQueue<T>[src]

type Item = Result<Expired<T>, Error>

Values yielded by the stream.

Auto Trait Implementations

impl<T> Send for DelayQueue<T> where
    T: Send

impl<T> Sync for DelayQueue<T> where
    T: Sync

impl<T> !UnwindSafe for DelayQueue<T>

impl<T> !RefUnwindSafe for DelayQueue<T>

Blanket Implementations

impl<T> From<T> for T[src]

impl<T, U> Into<U> for T where
    U: From<T>, 
[src]

impl<T, U> TryFrom<U> for T where
    U: Into<T>, 
[src]

type Error = Infallible

The type returned in the event of a conversion error.

impl<T, U> TryInto<U> for T where
    U: TryFrom<T>, 
[src]

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.

impl<T> Borrow<T> for T where
    T: ?Sized
[src]

impl<T> BorrowMut<T> for T where
    T: ?Sized
[src]

impl<T> Any for T where
    T: 'static + ?Sized
[src]

impl<S, T, E> TryStream for S where
    S: Stream<Item = Result<T, E>> + ?Sized
[src]

type Ok = T

The type of successful values yielded by this future

type Error = E

The type of failures yielded by this future

impl<T> StreamExt for T where
    T: Stream + ?Sized
[src]

fn next(&mut self) -> Next<Self> where
    Self: Unpin
[src]

Creates a future that resolves to the next item in the stream. Read more

fn into_future(self) -> StreamFuture<Self> where
    Self: Unpin
[src]

Converts this stream into a future of (next_item, tail_of_stream). If the stream terminates, then the next item is [None]. Read more

fn map<T, F>(self, f: F) -> Map<Self, F> where
    F: FnMut(Self::Item) -> T, 
[src]

Maps this stream's items to a different type, returning a new stream of the resulting type. Read more

fn enumerate(self) -> Enumerate<Self>[src]

Creates a stream which gives the current iteration count as well as the next value. Read more

fn filter<Fut, F>(self, f: F) -> Filter<Self, Fut, F> where
    F: FnMut(&Self::Item) -> Fut,
    Fut: Future<Output = bool>, 
[src]

Filters the values produced by this stream according to the provided asynchronous predicate. Read more

fn filter_map<Fut, T, F>(self, f: F) -> FilterMap<Self, Fut, F> where
    F: FnMut(Self::Item) -> Fut,
    Fut: Future<Output = Option<T>>, 
[src]

Filters the values produced by this stream while simultaneously mapping them to a different type according to the provided asynchronous closure. Read more

fn then<Fut, F>(self, f: F) -> Then<Self, Fut, F> where
    F: FnMut(Self::Item) -> Fut,
    Fut: Future
[src]

Computes from this stream's items new items of a different type using an asynchronous closure. Read more

fn collect<C>(self) -> Collect<Self, C> where
    C: Default + Extend<Self::Item>, 
[src]

Collect all of the values of this stream into a vector, returning a future representing the result of that computation. Read more

fn concat(self) -> Concat<Self> where
    Self::Item: Extend<<Self::Item as IntoIterator>::Item>,
    Self::Item: IntoIterator,
    Self::Item: Default
[src]

Concatenate all items of a stream into a single extendable destination, returning a future representing the end result. Read more

fn fold<T, Fut, F>(self, init: T, f: F) -> Fold<Self, Fut, T, F> where
    F: FnMut(T, Self::Item) -> Fut,
    Fut: Future<Output = T>, 
[src]

Execute an accumulating asynchronous computation over a stream, collecting all the values into one final result. Read more

fn flatten(self) -> Flatten<Self> where
    Self::Item: Stream
[src]

Flattens a stream of streams into just one continuous stream. Read more

fn skip_while<Fut, F>(self, f: F) -> SkipWhile<Self, Fut, F> where
    F: FnMut(&Self::Item) -> Fut,
    Fut: Future<Output = bool>, 
[src]

Skip elements on this stream while the provided asynchronous predicate resolves to true. Read more

fn take_while<Fut, F>(self, f: F) -> TakeWhile<Self, Fut, F> where
    F: FnMut(&Self::Item) -> Fut,
    Fut: Future<Output = bool>, 
[src]

Take elements from this stream while the provided asynchronous predicate resolves to true. Read more

fn for_each<Fut, F>(self, f: F) -> ForEach<Self, Fut, F> where
    F: FnMut(Self::Item) -> Fut,
    Fut: Future<Output = ()>, 
[src]

Runs this stream to completion, executing the provided asynchronous closure for each element on the stream. Read more

fn for_each_concurrent<Fut, F, impl Into>>(
    self,
    limit: impl Into>,
    f: F
) -> ForEachConcurrent<Self, Fut, F> where
    F: FnMut(Self::Item) -> Fut,
    Fut: Future<Output = ()>,
    impl Into>: Into<Option<usize>>, 
[src]

Runs this stream to completion, executing the provided asynchronous closure for each element on the stream concurrently as elements become available. Read more

fn take(self, n: u64) -> Take<Self>[src]

Creates a new stream of at most n items of the underlying stream. Read more

fn skip(self, n: u64) -> Skip<Self>[src]

Creates a new stream which skips n items of the underlying stream. Read more

fn fuse(self) -> Fuse<Self>[src]

Fuse a stream such that poll_next will never again be called once it has finished. This method can be used t turn any Stream into a FusedStream. Read more

fn by_ref(&mut self) -> &mut Self[src]

Borrows a stream, rather than consuming it. Read more

fn catch_unwind(self) -> CatchUnwind<Self> where
    Self: UnwindSafe
[src]

Catches unwinding panics while polling the stream. Read more

fn boxed<'a>(self) -> Pin<Box<dyn Stream<Item = Self::Item> + 'a + Send>> where
    Self: Send + 'a, 
[src]

Wrap the stream in a Box, pinning it. Read more

fn boxed_local<'a>(self) -> Pin<Box<dyn Stream<Item = Self::Item> + 'a>> where
    Self: 'a, 
[src]

Wrap the stream in a Box, pinning it. Read more

fn buffered(self, n: usize) -> Buffered<Self> where
    Self::Item: Future
[src]

An adaptor for creating a buffered list of pending futures. Read more

fn buffer_unordered(self, n: usize) -> BufferUnordered<Self> where
    Self::Item: Future
[src]

An adaptor for creating a buffered list of pending futures (unordered). Read more

fn zip<St>(self, other: St) -> Zip<Self, St> where
    St: Stream
[src]

An adapter for zipping two streams together. Read more

fn chain<St>(self, other: St) -> Chain<Self, St> where
    St: Stream<Item = Self::Item>, 
[src]

Adapter for chaining two stream. Read more

fn peekable(self) -> Peekable<Self>[src]

Creates a new stream which exposes a peek method. Read more

fn chunks(self, capacity: usize) -> Chunks<Self>[src]

An adaptor for chunking up items of the stream inside a vector. Read more

fn inspect<F>(self, f: F) -> Inspect<Self, F> where
    F: FnMut(&Self::Item), 
[src]

Do something with each item of this stream, afterwards passing it on. Read more

fn left_stream<B>(self) -> Either<Self, B> where
    B: Stream<Item = Self::Item>, 
[src]

Wrap this stream in an Either stream, making it the left-hand variant of that Either. Read more

fn right_stream<B>(self) -> Either<B, Self> where
    B: Stream<Item = Self::Item>, 
[src]

Wrap this stream in an Either stream, making it the right-hand variant of that Either. Read more

fn poll_next_unpin(&mut self, cx: &mut Context) -> Poll<Option<Self::Item>> where
    Self: Unpin
[src]

A convenience method for calling [Stream::poll_next] on [Unpin] stream types. Read more

fn select_next_some(&mut self) -> SelectNextSome<Self> where
    Self: Unpin + FusedStream
[src]

Returns a [Future] that resolves when the next item in this stream is ready. Read more

impl<S> TryStreamExt for S where
    S: TryStream + ?Sized
[src]

fn err_into<E>(self) -> ErrInto<Self, E> where
    Self::Error: Into<E>, 
[src]

Wraps the current stream in a new stream which converts the error type into the one provided. Read more

fn map_ok<T, F>(self, f: F) -> MapOk<Self, F> where
    F: FnMut(Self::Ok) -> T, 
[src]

Wraps the current stream in a new stream which maps the success value using the provided closure. Read more

fn map_err<E, F>(self, f: F) -> MapErr<Self, F> where
    F: FnMut(Self::Error) -> E, 
[src]

Wraps the current stream in a new stream which maps the error value using the provided closure. Read more

fn and_then<Fut, F>(self, f: F) -> AndThen<Self, Fut, F> where
    F: FnMut(Self::Ok) -> Fut,
    Fut: TryFuture<Error = Self::Error>, 
[src]

Chain on a computation for when a value is ready, passing the successful results to the provided closure f. Read more

fn or_else<Fut, F>(self, f: F) -> OrElse<Self, Fut, F> where
    F: FnMut(Self::Error) -> Fut,
    Fut: TryFuture<Ok = Self::Ok>, 
[src]

Chain on a computation for when an error happens, passing the erroneous result to the provided closure f. Read more

fn inspect_ok<F>(self, f: F) -> InspectOk<Self, F> where
    F: FnMut(&Self::Ok), 
[src]

Do something with the success value of this stream, afterwards passing it on. Read more

fn inspect_err<F>(self, f: F) -> InspectErr<Self, F> where
    F: FnMut(&Self::Error), 
[src]

Do something with the error value of this stream, afterwards passing it on. Read more

fn into_stream(self) -> IntoStream<Self>[src]

Wraps a [TryStream] into a type that implements Stream Read more

fn try_next(&mut self) -> TryNext<Self> where
    Self: Unpin
[src]

Creates a future that attempts to resolve the next item in the stream. If an error is encountered before the next item, the error is returned instead. Read more

fn try_for_each<Fut, F>(self, f: F) -> TryForEach<Self, Fut, F> where
    F: FnMut(Self::Ok) -> Fut,
    Fut: TryFuture<Ok = (), Error = Self::Error>, 
[src]

Attempts to run this stream to completion, executing the provided asynchronous closure for each element on the stream. Read more

fn try_skip_while<Fut, F>(self, f: F) -> TrySkipWhile<Self, Fut, F> where
    F: FnMut(&Self::Ok) -> Fut,
    Fut: TryFuture<Ok = bool, Error = Self::Error>, 
[src]

Skip elements on this stream while the provided asynchronous predicate resolves to true. Read more

fn try_for_each_concurrent<Fut, F, impl Into>>(
    self,
    limit: impl Into>,
    f: F
) -> TryForEachConcurrent<Self, Fut, F> where
    F: FnMut(Self::Ok) -> Fut,
    Fut: Future<Output = Result<(), Self::Error>>,
    impl Into>: Into<Option<usize>>, 
[src]

Attempts to run this stream to completion, executing the provided asynchronous closure for each element on the stream concurrently as elements become available, exiting as soon as an error occurs. Read more

fn try_collect<C>(self) -> TryCollect<Self, C> where
    C: Default + Extend<Self::Ok>, 
[src]

Attempt to Collect all of the values of this stream into a vector, returning a future representing the result of that computation. Read more

fn try_filter<Fut, F>(self, f: F) -> TryFilter<Self, Fut, F> where
    F: FnMut(&Self::Ok) -> Fut,
    Fut: Future<Output = bool>, 
[src]

Attempt to filter the values produced by this stream according to the provided asynchronous closure. Read more

fn try_filter_map<Fut, F, T>(self, f: F) -> TryFilterMap<Self, Fut, F> where
    F: FnMut(Self::Ok) -> Fut,
    Fut: TryFuture<Ok = Option<T>, Error = Self::Error>, 
[src]

Attempt to filter the values produced by this stream while simultaneously mapping them to a different type according to the provided asynchronous closure. Read more

fn try_flatten(self) -> TryFlatten<Self> where
    Self::Ok: TryStream,
    <Self::Ok as TryStream>::Error: From<Self::Error>, 
[src]

Flattens a stream of streams into just one continuous stream. Read more

fn try_fold<T, Fut, F>(self, init: T, f: F) -> TryFold<Self, Fut, T, F> where
    F: FnMut(T, Self::Ok) -> Fut,
    Fut: TryFuture<Ok = T, Error = Self::Error>, 
[src]

Attempt to execute an accumulating asynchronous computation over a stream, collecting all the values into one final result. Read more

fn try_concat(self) -> TryConcat<Self> where
    Self::Ok: Extend<<Self::Ok as IntoIterator>::Item>,
    Self::Ok: IntoIterator,
    Self::Ok: Default
[src]

Attempt to concatenate all items of a stream into a single extendable destination, returning a future representing the end result. Read more

fn try_buffer_unordered(self, n: usize) -> TryBufferUnordered<Self> where
    Self::Ok: TryFuture,
    <Self::Ok as TryFuture>::Error == Self::Error
[src]

Attempt to execute several futures from a stream concurrently. Read more

fn try_poll_next_unpin(
    &mut self,
    cx: &mut Context
) -> Poll<Option<Result<Self::Ok, Self::Error>>> where
    Self: Unpin
[src]

A convenience method for calling [TryStream::try_poll_next] on [Unpin] stream types. Read more