Struct Timer

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

Timer store all timeout callback base on binaryHeap; The callback function will be triggered when the time expires

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§

Source§

impl Timer

Source

pub fn new() -> Self

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);
Examples found in repository?
examples/async_timeout.rs (line 6)
5fn main() {
6    let timer = Timer::new();
7
8    // this future print count every 1 sec
9    let async_block = async {
10        let mut count = 1;
11        loop {
12            timer.wait(Duration::from_secs(1)).await;
13            count += 1;
14            println!("{count}");
15        }
16    };
17}
More examples
Hide additional examples
examples/interval.rs (line 12)
11fn main() {
12    let timer = Timer::new();
13    let count: Arc<AtomicUsize> = Default::default();
14    let count_clone = count.clone();
15    // count will increase every 1 sec
16    let _ = timer.set_interval(
17        move || {
18            count_clone.fetch_add(1, SeqCst);
19            println!("run callback success");
20        },
21        Duration::from_secs(2),
22    );
23
24    sleep(Duration::from_secs(5));
25
26    assert_eq!(count.load(SeqCst), 2);
27}
examples/timeout.rs (line 15)
14fn main() {
15    let timer = Timer::new();
16    let count = Arc::new(AtomicUsize::new(0));
17    let count_clone = count.clone();
18    // count will increase after 1 sec
19    let _ = timer.set_timeout(
20        move || {
21            count_clone.fetch_add(1, SeqCst);
22            println!("run callback success");
23        },
24        Duration::from_secs(1),
25    );
26
27    sleep(Duration::from_secs(1) + Duration::from_millis(20));
28
29    assert_eq!(count.load(SeqCst), 1);
30
31    let count_clone = count.clone();
32    let cancel_timeout = timer.set_timeout(
33        move || {
34            count_clone.fetch_add(1, SeqCst);
35            println!("run callback success");
36        },
37        Duration::from_secs(1),
38    );
39
40    sleep(Duration::from_millis(20));
41    // cancel callback;
42    cancel_timeout();
43    sleep(Duration::from_secs(1));
44    // count still be 1;
45    assert_eq!(count.load(SeqCst), 1);
46}
Source

pub fn set_timeout( &self, callback: impl FnOnce() + 'static + Send, duration: Duration, ) -> impl FnOnce() + Sync + 'static

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));
Examples found in repository?
examples/timeout.rs (lines 19-25)
14fn main() {
15    let timer = Timer::new();
16    let count = Arc::new(AtomicUsize::new(0));
17    let count_clone = count.clone();
18    // count will increase after 1 sec
19    let _ = timer.set_timeout(
20        move || {
21            count_clone.fetch_add(1, SeqCst);
22            println!("run callback success");
23        },
24        Duration::from_secs(1),
25    );
26
27    sleep(Duration::from_secs(1) + Duration::from_millis(20));
28
29    assert_eq!(count.load(SeqCst), 1);
30
31    let count_clone = count.clone();
32    let cancel_timeout = timer.set_timeout(
33        move || {
34            count_clone.fetch_add(1, SeqCst);
35            println!("run callback success");
36        },
37        Duration::from_secs(1),
38    );
39
40    sleep(Duration::from_millis(20));
41    // cancel callback;
42    cancel_timeout();
43    sleep(Duration::from_secs(1));
44    // count still be 1;
45    assert_eq!(count.load(SeqCst), 1);
46}
Source

pub fn set_interval( &self, callback: impl FnMut() + 'static + Send, duration: Duration, ) -> impl FnOnce() + Sync + 'static

set_interval is basically consistent with set_timeout callback will run every duration; if you want to cancel interval, set_interval return cancel function, run it will cancel current interval callback;

§Examples

set_interval:

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

let timer = Timer::new();

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

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

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

cancel_interval:

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

let timer = Timer::new();

let cancel = timer.set_interval(||{
    println!("every 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(7));
Examples found in repository?
examples/interval.rs (lines 16-22)
11fn main() {
12    let timer = Timer::new();
13    let count: Arc<AtomicUsize> = Default::default();
14    let count_clone = count.clone();
15    // count will increase every 1 sec
16    let _ = timer.set_interval(
17        move || {
18            count_clone.fetch_add(1, SeqCst);
19            println!("run callback success");
20        },
21        Duration::from_secs(2),
22    );
23
24    sleep(Duration::from_secs(5));
25
26    assert_eq!(count.load(SeqCst), 2);
27}
Source

pub async fn wait(&self, duration: Duration)

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);
Examples found in repository?
examples/async_timeout.rs (line 12)
5fn main() {
6    let timer = Timer::new();
7
8    // this future print count every 1 sec
9    let async_block = async {
10        let mut count = 1;
11        loop {
12            timer.wait(Duration::from_secs(1)).await;
13            count += 1;
14            println!("{count}");
15        }
16    };
17}

Trait Implementations§

Source§

impl Default for Timer

Source§

fn default() -> Self

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

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.