【发布时间】: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 功能(可能作为服务)?
谢谢!
【问题讨论】:
-
使用
actix::spawn启动一个任务,在循环中使用tokio::time::delay_for等待10s并执行ping? -
还有一个
run_interval,它“生成一个作业,以指定的固定间隔定期执行给定的闭包。”