broker_tokio::time

Struct DelayQueue

Source
pub struct DelayQueue<T> { /* private fields */ }
Available on crate feature time only.
Expand description

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::time::{delay_queue, DelayQueue, Error};

use futures::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_expired(cx)) {
            let entry = res?;
            self.entries.remove(entry.get_ref());
        }

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

Implementations§

Source§

impl<T> DelayQueue<T>

Source

pub fn new() -> DelayQueue<T>

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();
Source

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

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));
Source

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

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::time::{DelayQueue, Duration, Instant};

    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");
Source

pub fn poll_expired( &mut self, cx: &mut Context<'_>, ) -> Poll<Option<Result<Expired<T>, Error>>>

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.

Source

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

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::time::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");
Source

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

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::time::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");
Source

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

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::time::{DelayQueue, 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
Source

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

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::time::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
Source

pub fn clear(&mut self)

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::time::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());
Source

pub fn capacity(&self) -> usize

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

§Examples
use tokio::time::DelayQueue;

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

pub fn len(&self) -> usize

Returns the number of elements currently in the queue.

§Examples
use tokio::time::DelayQueue;
use std::time::Duration;

    let mut delay_queue: DelayQueue<i32> = DelayQueue::with_capacity(10);
    assert_eq!(delay_queue.len(), 0);
    delay_queue.insert(3, Duration::from_secs(5));
    assert_eq!(delay_queue.len(), 1);
Source

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

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::time::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);
Source

pub fn is_empty(&self) -> bool

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::time::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§

Source§

impl<T: Debug> Debug for DelayQueue<T>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<T> Default for DelayQueue<T>

Source§

fn default() -> DelayQueue<T>

Returns the “default value” for a type. Read more
Source§

impl<T> Stream for DelayQueue<T>

Source§

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

Values yielded by the stream.
Source§

fn poll_next( self: Pin<&mut Self>, cx: &mut Context<'_>, ) -> Poll<Option<Self::Item>>

Attempt to pull out the next value of this stream, registering the current task for wakeup if the value is not yet available, and returning None if the stream is exhausted. Read more
Source§

fn size_hint(&self) -> (usize, Option<usize>)

Returns the bounds on the remaining length of the stream. Read more
Source§

impl<T> Unpin for DelayQueue<T>

Auto Trait Implementations§

§

impl<T> Freeze for DelayQueue<T>

§

impl<T> !RefUnwindSafe for DelayQueue<T>

§

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

§

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

§

impl<T> !UnwindSafe for DelayQueue<T>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<St> StreamExt for St
where St: Stream + ?Sized,

Source§

fn next(&mut self) -> Next<'_, Self>
where Self: Unpin,

Available on crate feature stream only.
Consumes and returns the next value in the stream or None if the stream is finished. Read more
Source§

fn try_next<T, E>(&mut self) -> TryNext<'_, Self>
where Self: Stream<Item = Result<T, E>> + Unpin,

Available on crate feature stream only.
Consumes and returns the next item in the stream. If an error is encountered before the next item, the error is returned instead. Read more
Source§

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

Available on crate feature stream only.
Maps this stream’s items to a different type, returning a new stream of the resulting type. Read more
Source§

fn merge<U>(self, other: U) -> Merge<Self, U>
where U: Stream<Item = Self::Item>, Self: Sized,

Available on crate feature stream only.
Combine two streams into one by interleaving the output of both as it is produced. Read more
Source§

fn filter<F>(self, f: F) -> Filter<Self, F>
where F: FnMut(&Self::Item) -> bool, Self: Sized,

Available on crate feature stream only.
Filters the values produced by this stream according to the provided predicate. Read more
Source§

fn filter_map<T, F>(self, f: F) -> FilterMap<Self, F>
where F: FnMut(Self::Item) -> Option<T>, Self: Sized,

Available on crate feature stream only.
Filters the values produced by this stream while simultaneously mapping them to a different type according to the provided closure. Read more
Source§

fn fuse(self) -> Fuse<Self>
where Self: Sized,

Available on crate feature stream only.
Creates a stream which ends after the first None. Read more
Source§

fn take(self, n: usize) -> Take<Self>
where Self: Sized,

Available on crate feature stream only.
Creates a new stream of at most n items of the underlying stream. Read more
Source§

fn take_while<F>(self, f: F) -> TakeWhile<Self, F>
where F: FnMut(&Self::Item) -> bool, Self: Sized,

Available on crate feature stream only.
Take elements from this stream while the provided predicate resolves to true. Read more
Source§

fn all<F>(&mut self, f: F) -> AllFuture<'_, Self, F>
where Self: Unpin, F: FnMut(Self::Item) -> bool,

Available on crate feature stream only.
Tests if every element of the stream matches a predicate. Read more
Source§

fn any<F>(&mut self, f: F) -> AnyFuture<'_, Self, F>
where Self: Unpin, F: FnMut(Self::Item) -> bool,

Available on crate feature stream only.
Tests if any element of the stream matches a predicate. Read more
Source§

fn chain<U>(self, other: U) -> Chain<Self, U>
where U: Stream<Item = Self::Item>, Self: Sized,

Available on crate feature stream only.
Combine two streams into one by first returning all values from the first stream then all values from the second stream. Read more
Source§

fn collect<T>(self) -> Collect<Self, T>
where T: FromStream<Self::Item>, Self: Sized,

Available on crate feature stream only.
Drain stream pushing all emitted values into a collection. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

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

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

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

Source§

type Ok = T

The type of successful values yielded by this future
Source§

type Error = E

The type of failures yielded by this future
Source§

fn try_poll_next( self: Pin<&mut S>, cx: &mut Context<'_>, ) -> Poll<Option<Result<<S as TryStream>::Ok, <S as TryStream>::Error>>>

Poll this TryStream as if it were a Stream. Read more