Struct ThreadTimer

Source
pub struct ThreadTimer { /* private fields */ }
Expand description

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

Implementations§

Source§

impl ThreadTimer

Source

pub fn new() -> Self

Creates and returns a new ThreadTimer. Spawns a new thread to do the waiting (the “wait thread”).

use thread_timer::ThreadTimer;
let timer = ThreadTimer::new();
Source

pub fn start<F>(&self, dur: Duration, f: F) -> Result<(), TimerStartError>
where F: FnOnce() + Send + 'static,

Start waiting. Wait for dur to elapse then execute f. Will not execute f if the timer is canceled before dur elapses. Returns TimerStartError::AlreadyWaiting if the timer is already waiting to execute a thunk.

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();
assert_eq!(
  receiver.try_recv(),
  Err(TryRecvError::Empty),
  "Received response before wait elapsed!",
);

thread::sleep(Duration::from_millis(60));
assert_eq!(
  receiver.try_recv(),
  Ok(true),
  "Did not receive response after wait elapsed!",
);
Source

pub fn cancel(&self) -> Result<(), TimerCancelError>

Cancel the current timer (the thunk will not be executed and the timer will be able to start waiting to execute another thunk). This function waits until the wait thread has confirmed that it is ready to start waiting again, so it is safe to call start immediately after calling this function. Returns TimerCancelError::NotWaiting if the timer is not currently waiting.

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

// Make sure the wait has actually started before we cancel
thread::sleep(Duration::from_millis(10));
timer.cancel().unwrap();

thread::sleep(Duration::from_millis(60));
assert_eq!(
  receiver.try_recv(),
  // When the wait is canceled, the thunk and its Sender will be dropped
  Err(TryRecvError::Disconnected),
  "Received response from canceled wait!",
);

Trait Implementations§

Source§

impl Clone for ThreadTimer

Source§

fn clone(&self) -> ThreadTimer

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Default for ThreadTimer

Source§

fn default() -> Self

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

Auto Trait Implementations§

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> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. 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<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. 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.