Crates.io | thread_timer |
lib.rs | thread_timer |
version | 0.3.0 |
source | src |
created_at | 2020-08-02 04:59:27.954524 |
updated_at | 2020-10-07 20:31:14.377099 |
description | A simple, cancelable timer with no external dependencies |
homepage | https://github.com/GregOwen/thread-timer |
repository | https://github.com/GregOwen/thread-timer |
max_upload_size | |
id | 272138 |
size | 17,338 |
A simple, cancelable timer implementation with no external dependencies.
The main interface of this crate is the struct ThreadTimer
, which is a simple,
cancelable timer that can run a thunk after waiting for an arbitrary duration.
Waiting is accomplished by using a helper thread (the "wait thread") that
listens for incoming wait requests and then executes the requested thunk after
blocking for the requested duration. Because each ThreadTimer
keeps only one
wait thread, each ThreadTimer
may only be waiting for a single thunk at a
time.
use std::sync::mpsc::{self, TryRecvError};
use std::thread;
use std::time::Duration;
use thread_timer::ThreadTimer;
let (sender, receiver) = mpsc::channel::<bool>();
let timer = ThreadTimer::new();
timer.start(Duration::from_millis(50), move || { sender.send(true).unwrap() }).unwrap();
thread::sleep(Duration::from_millis(60));
assert_eq!(receiver.try_recv(), Ok(true));
If a ThreadTimer is currently waiting to execute a thunk, the wait can be canceled, in which case the thunk will not be run.
use std::sync::mpsc::{self, TryRecvError};
use std::thread;
use std::time::Duration;
use thread_timer::ThreadTimer;
let (sender, receiver) = mpsc::channel::<bool>();
let timer = ThreadTimer::new();
timer.start(Duration::from_millis(50), move || { sender.send(true).unwrap() }).unwrap();
thread::sleep(Duration::from_millis(10));
timer.cancel().unwrap();
thread::sleep(Duration::from_millis(60));
assert_eq!(receiver.try_recv(), Err(TryRecvError::Disconnected));