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

Timer store all timeout callback base on binaryHeap; will duration is reach

Example

use swnb_timer::Timer;
use std::time::Duration;

let timer = Timer::new();

timer.set_timeout(||{
    println!("after 1 sec");
},Duration::from_secs(1));

std::thread::sleep(Duration::from_secs(2));

Implementations

create new Timer, this method will create one thread to handle all task base on binaryHeap;

Examples

Basic usage:

use swnb_timer::Timer;
use std::time::Duration;

let timer = Timer::new();

timer.set_timeout(||{
    println!("after 1 sec");
},Duration::from_secs(1));

timer.set_timeout(||{
    println!("after 2 sec");
},Duration::from_secs(2));

std::thread::sleep(Duration::from_secs(3));

Async usage:

use swnb_timer::Timer;
use std::time::Duration;

let timer = Timer::new();

let async_block = async {
    timer.wait(Duration::from_secs(1)).await;
    println!("after 1 sec");
};
// blocking_on(async_block);

set_timeout accept two arguments, callback and duration; callback will run after duration; if you want to cancel callback before the deadline, set_timeout return cancel function, run it will cancel current timeout callback;

Examples

set_timeout:

use swnb_timer::Timer;
use std::time::Duration;

let timer = Timer::new();

timer.set_timeout(||{
    println!("after 1 sec");
},Duration::from_secs(1));

timer.set_timeout(||{
    println!("after 2 sec");
},Duration::from_secs(2));

std::thread::sleep(Duration::from_secs(3));

cancel_callback:

use swnb_timer::Timer;
use std::time::Duration;

let timer = Timer::new();

let cancel = timer.set_timeout(||{
    println!("after 2 sec");
},Duration::from_secs(2));

timer.set_timeout(move ||{
   cancel();
   println!("cancel previous timeout callback");
},Duration::from_secs(1));

std::thread::sleep(Duration::from_secs(3));

wait for duration time

Examples

use swnb_timer::Timer;
use std::time::Duration;

let timer = Timer::new();

let async_block = async {
    timer.wait(Duration::from_secs(1)).await;
};

// blocking_on(async_block);

Trait Implementations

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

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.