我目前正在使用 Rust 和 Actix-Web 实现一个服务器。我现在的任务是每 10 秒从这台服务器向另一台服务器发送一个请求(ping 请求)。ping 请求本身是在一个async函数中实现的:
async fn ping(client: web::Data<Client>, state: Data<AppState>) -> Result<HttpResponse, Error> {}
Run Code Online (Sandbox Code Playgroud)
这是我的简单服务器主功能:
#[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
}
Run Code Online (Sandbox Code Playgroud)
我尝试使用tokio,但这太复杂了,因为所有不同的异步函数及其生命周期。
那么在服务器启动后每 10 秒,actix-web 中是否有任何简单的方法来执行此 ping 功能(可能作为服务)?
谢谢!
见actix_rt::spawn和actix_rt::time::interval。
下面是一个例子:
spawn(async move {
let mut interval = time::interval(Duration::from_secs(10));
loop {
interval.tick().await;
// do something
}
});
Run Code Online (Sandbox Code Playgroud)