#timer #timeout #interval #async

swnb-timer

一个可以注册超时和间隔回调的库,支持同步和异步风格的 API

4 个版本

0.2.0 2023 年 2 月 20 日
0.1.2 2022 年 11 月 1 日
0.1.1 2022 年 11 月 1 日
0.1.0 2022 年 10 月 31 日

#25#timeout

自定义许可证

18KB
319

timer-rs

timer 可以在等待指定时间后执行一个函数,也支持异步风格的 API

安装

  cargo add swnb-timer

设置超时回调

use std::{
    sync::{atomic::AtomicUsize, Arc},
    time::Duration,
};

use std::sync::atomic::Ordering::SeqCst;

use swnb_timer::Timer;

fn main(){
    let timer = Timer::new();
    let count = Arc::new(AtomicUsize::new(0));
    let count_clone = count.clone();
    let duration = Duration::from_secs(1);
    // count will increase after 1 sec
    let _ = timer.set_timeout(
        move || {
            count_clone.fetch_add(1, SeqCst);
            println!("run callback success");
        },
        duration,
    );

    std::thread::sleep(Duration::from_secs(2));
    assert_eq!(count.load(SeqCst), 1);
}

取消回调

use std::{
    sync::{atomic::AtomicUsize, Arc},
    time::Duration,
};

use std::sync::atomic::Ordering::SeqCst;

use swnb_timer::Timer;

fn sleep(duration: Duration) {
    std::thread::sleep(duration);
}

fn main() {
    let timer = Timer::new();
    let count = Arc::new(AtomicUsize::new(1));
    let count_clone = count.clone();
    let cancel_timeout = timer.set_timeout(
        move || {
            count_clone.fetch_add(1, SeqCst);
            println!("run callback success");
        },
        Duration::from_secs(1),
    );

    sleep(Duration::from_millis(20));
    // cancel timeout callback;
    cancel_timeout();
    sleep(Duration::from_secs(1));
    // count still be 1;
    assert_eq!(count.load(SeqCst), 1);
}

使用异步函数;

use std::time::Duration;

use swnb_timer::Timer;

async fn main() {
    let timer = Timer::new();

    // print count every 1 sec
    let async_block = async {
        let mut count = 1;
        loop {
            timer.wait(Duration::from_secs(1)).await;
            count += 1;
            println!("{count}");
        }
    };

    async_block.await;
}

无运行时依赖