#shutdown-signal #numbers #task #tokio #fixed #repeatedly #run

evermore

一个库,允许你反复运行固定数量的异步任务,直到发送关闭信号。

1个不稳定版本

0.1.0 2022年7月29日

#1607 in 异步

MIT 许可证

17KB
308

(stry) evermore

Evermore是一个库,允许你反复运行固定数量的异步任务,直到发送关闭信号。

示例

Evermore与Tokio、ctrlc和tracing的使用。

use stry_evermore::{Evermore, Worker};

#[derive(Clone, Debug, Default)]
struct Data {}

#[tokio::main]
async fn main() {
    tracing_subscriber::fmt()
        .with_max_level(tracing::Level::TRACE)
        .with_target(true)
        .init();

    let (tx, mut rx) = tokio::sync::broadcast::channel(1);

    ctrlc::set_handler(move || {
        if tx.send(()).is_err() {
            tracing::error!("Unable to send shutdown signal");
        }
    })
    .expect("Unable to set CTRL-C handler");

    let signal = async move { rx.recv().await.expect("Failed to listen for event") };

    Evermore::new(signal, 4, Data::default(), |data: Worker<Data>| {
        Box::pin(task(data))
    })
    .await;
}

#[tracing::instrument(skip(data))]
async fn task(worker: Worker<Data>) -> Result<(), std::io::Error> {
    loop {
        tokio::time::delay_for(tokio::time::Duration::from_millis(1)).await;

        if worker.should_stop() {
            tracing::info!("Received shutdown signal, shutting down");

            break;
        }
    }

    Ok(())
}

依赖项

~0.3–0.9MB
~19K SLoC