Struct Timer

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

A timer, used to schedule execution of callbacks at a later date.

In the current implementation, each timer is executed as two threads. The Scheduler thread is in charge of maintaining the queue of callbacks to execute and of actually executing them. The Communication thread is in charge of communicating with the Scheduler thread (which requires acquiring a possibly-long-held Mutex) without blocking the caller thread.

Implementations§

Source§

impl Timer

Source

pub fn new() -> Self

Create a timer.

This immediatey launches two threads, which will remain launched until the timer is dropped. As expected, the threads spend most of their life waiting for instructions.

Source

pub fn with_capacity(capacity: usize) -> Self

As new(), but with a manually specified initial capaicty.

Source

pub fn schedule_with_delay<F>(&self, delay: Duration, cb: F) -> Guard
where F: 'static + FnMut() + Send,

Schedule a callback for execution after a delay.

Callbacks are guaranteed to never be called before the delay. However, it is possible that they will be called a little after the delay.

If the delay is negative or 0, the callback is executed as soon as possible.

This method returns a Guard object. If that Guard is dropped, execution is cancelled.

§Performance

The callback is executed on the Scheduler thread. It should therefore terminate very quickly, or risk causing delaying other callbacks.

§Failures

Any failure in cb will scheduler thread and progressively contaminate the Timer and the calling thread itself. You have been warned.

§Example
extern crate timer;
extern crate chrono;
use std::sync::mpsc::channel;

let timer = timer::Timer::new();
let (tx, rx) = channel();

let _guard = timer.schedule_with_delay(chrono::Duration::seconds(3), move || {
  // This closure is executed on the scheduler thread,
  // so we want to move it away asap.

  let _ignored = tx.send(()); // Avoid unwrapping here.
});

rx.recv().unwrap();
println!("This code has been executed after 3 seconds");
Source

pub fn schedule_with_date<F, T>(&self, date: DateTime<T>, cb: F) -> Guard
where F: 'static + FnMut() + Send, T: TimeZone,

Schedule a callback for execution at a given date.

Callbacks are guaranteed to never be called before their date. However, it is possible that they will be called a little after it.

If the date is in the past, the callback is executed as soon as possible.

This method returns a Guard object. If that Guard is dropped, execution is cancelled.

§Performance

The callback is executed on the Scheduler thread. It should therefore terminate very quickly, or risk causing delaying other callbacks.

§Failures

Any failure in cb will scheduler thread and progressively contaminate the Timer and the calling thread itself. You have been warned.

Source

pub fn schedule_repeating<F>(&self, repeat: Duration, cb: F) -> Guard
where F: 'static + FnMut() + Send,

Schedule a callback for execution once per interval.

Callbacks are guaranteed to never be called before their date. However, it is possible that they will be called a little after it.

This method returns a Guard object. If that Guard is dropped, repeat is stopped.

§Performance

The callback is executed on the Scheduler thread. It should therefore terminate very quickly, or risk causing delaying other callbacks.

§Failures

Any failure in cb will scheduler thread and progressively contaminate the Timer and the calling thread itself. You have been warned.

§Example
extern crate timer;
extern crate chrono;
use std::thread;
use std::sync::{Arc, Mutex};

let timer = timer::Timer::new();
// Number of times the callback has been called.
let count = Arc::new(Mutex::new(0));

// Start repeating. Each callback increases `count`.
let guard = {
  let count = count.clone();
  timer.schedule_repeating(chrono::Duration::milliseconds(5), move || {
    *count.lock().unwrap() += 1;
  })
};

// Sleep one second. The callback should be called ~200 times.
thread::sleep(std::time::Duration::new(1, 0));
let count_result = *count.lock().unwrap();
assert!(190 <= count_result && count_result <= 210,
  "The timer was called {} times", count_result);

// Now drop the guard. This should stop the timer.
drop(guard);
thread::sleep(std::time::Duration::new(0, 100));

// Let's check that the count stops increasing.
let count_start = *count.lock().unwrap();
thread::sleep(std::time::Duration::new(1, 0));
let count_stop =  *count.lock().unwrap();
assert_eq!(count_start, count_stop);
Source

pub fn schedule<F, T>( &self, date: DateTime<T>, repeat: Option<Duration>, cb: F, ) -> Guard
where F: 'static + FnMut() + Send, T: TimeZone,

Schedule a callback for execution at a given time, then once per interval. A typical use case is to execute code once per day at 12am.

Callbacks are guaranteed to never be called before their date. However, it is possible that they will be called a little after it.

This method returns a Guard object. If that Guard is dropped, repeat is stopped.

§Performance

The callback is executed on the Scheduler thread. It should therefore terminate very quickly, or risk causing delaying other callbacks.

§Failures

Any failure in cb will scheduler thread and progressively contaminate the Timer and the calling thread itself. You have been warned.

Auto Trait Implementations§

§

impl Freeze for Timer

§

impl RefUnwindSafe for Timer

§

impl Send for Timer

§

impl Sync for Timer

§

impl Unpin for Timer

§

impl UnwindSafe for Timer

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> 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, 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.