pub fn after(duration: Duration) -> Receiver<Instant>
Expand description

Creates a receiver that delivers a message after a certain duration of time.

The channel is bounded with capacity of 1 and never gets disconnected. Exactly one message will be sent into the channel after duration elapses. The message is the instant at which it is sent.

Examples

Using an after channel for timeouts:

use std::time::Duration;
use crossbeam_channel::{after, select, unbounded};

let (s, r) = unbounded::<i32>();
let timeout = Duration::from_millis(100);

select! {
    recv(r) -> msg => println!("received {:?}", msg),
    recv(after(timeout)) -> _ => println!("timed out"),
}

When the message gets sent:

use std::thread;
use std::time::{Duration, Instant};
use crossbeam_channel::after;

// Converts a number of milliseconds into a `Duration`.
let ms = |ms| Duration::from_millis(ms);

// Returns `true` if `a` and `b` are very close `Instant`s.
let eq = |a, b| a + ms(50) > b && b + ms(50) > a;

let start = Instant::now();
let r = after(ms(100));

thread::sleep(ms(500));

// This message was sent 100 ms from the start and received 500 ms from the start.
assert!(eq(r.recv().unwrap(), start + ms(100)));
assert!(eq(Instant::now(), start + ms(500)));