Function crossbeam::channel::tick

source ·
pub fn tick(duration: Duration) -> Receiver<Instant>
Expand description

Creates a receiver that delivers messages periodically.

The channel is bounded with capacity of 1 and never gets disconnected. Messages will be sent into the channel in intervals of duration. Each message is the instant at which it is sent.

§Examples

Using a tick channel to periodically print elapsed time:

use std::time::{Duration, Instant};
use crossbeam_channel::tick;

let start = Instant::now();
let ticker = tick(Duration::from_millis(100));

for _ in 0..5 {
    ticker.recv().unwrap();
    println!("elapsed: {:?}", start.elapsed());
}

When messages get sent:

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

// 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(65) > b && b + ms(65) > a;

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

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

thread::sleep(ms(500));

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

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