Skip to content

A simple, cancelable timer with no external dependencies

License

Notifications You must be signed in to change notification settings

GregOwen/thread-timer

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

20 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

thread_timer

A simple, cancelable timer implementation with no external dependencies.

License

ThreadTimer

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

About

A simple, cancelable timer with no external dependencies

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Languages