Struct swnb_timer::Timer
source · [−]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
sourceimpl Timer
impl Timer
sourcepub fn new() -> Self
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);sourcepub fn set_timeout(
&self,
callback: impl FnOnce() + 'static + Send,
duration: Duration
) -> impl FnOnce() + Sync + 'static
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));Trait Implementations
Auto Trait Implementations
impl !RefUnwindSafe for Timer
impl Send for Timer
impl Sync for Timer
impl Unpin for Timer
impl !UnwindSafe for Timer
Blanket Implementations
sourceimpl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
const: unstable · sourcefn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more