【问题标题】:Actix-Web: Run service every 10 secondsActix-Web:每 10 秒运行一次服务
【发布时间】:2021-03-26 02:50:44
【问题描述】:

我目前正在使用 Rust 和 Actix-Web 实现服务器。我现在的任务是每 10 秒从该服务器向另一台服务器发送一个请求(ping-request)。 ping-request 本身在 async 函数中实现:

async fn ping(client: web::Data<Client>, state: Data<AppState>) -> Result<HttpResponse, Error> {}

这是我的简单服务器主函数:

#[actix_rt::main]
async fn main() -> std::io::Result<()> {
    ::std::env::set_var("RUST_LOG", "debug");
    env_logger::init();
    let args = config::CliOptions::from_args();
    let config =
        config::Config::new(args.config_file.as_path()).expect("Failed to config");
    let address = config.address.clone();
    let app_state = AppState::new(config).unwrap();

    println!("Started http server: http://{}", address);

    HttpServer::new(move || {
        App::new()
            .data(app_state.clone())
            .app_data(app_state.clone())
            .data(Client::default())
            .default_service(web::resource("/").route(web::get().to(index)))
    })
    .bind(address)?
    .run()
    .await
}

我尝试使用tokio,但这太复杂了,因为所有不同的异步函数及其生命周期。

那么在服务器启动后,actix-web 中是否有任何简单的方法可以每 10 秒执行一次这个 ping 功能(可能作为服务)?

谢谢!

【问题讨论】:

标签: rust actix-web


【解决方案1】:

参见actix_rt::spawnactix_rt::time::interval

这是一个例子:

spawn(async move {
    let mut interval = time::interval(Duration::from_secs(10));
    loop {
        interval.tick().await;
        // do something
    }
});

【讨论】:

    【解决方案2】:
    #[get("/run_c")]
    async fn run_c() -> impl Responder {
        //tokio::time::delay_until(Duration::from_secs(5)).await;
        //time::interval(period)
        let mut interval = time::interval(Duration::from_millis(10));
        loop {
            interval.tick().await;
            print!("hello");
            HttpResponse::Ok().body("Hello world!");
        }
    
    }
    

    这可行,但唯一的事情是它不会将 http 响应返回给调用者

    【讨论】:

      猜你喜欢
      • 2018-11-08
      • 1970-01-01
      • 2022-01-11
      • 1970-01-01
      • 1970-01-01
      • 2012-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多