I'm currently implementing a server using Rust and Actix-Web. My task now is to send a request (ping-request) from this server to another server every 10 seconds. The ping-request itself is implemented in a async
function:
async fn ping(client: web::Data<Client>, state: Data<AppState>) -> Result<HttpResponse, Error> {}
This is my simple server-main-function:
#[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
}
I tried using tokio
, but this was just to complicated because all the different async function and their lifetimes.
So is there any easy way within actix-web to execute this ping-function (maybe as a service) every 10 seconds after the server started?
Thanks!
actix::spawn
to start a task that usestokio::time::delay_for
in a loop to wait for 10s and execute the ping? – Jmbrun_interval
which "Spawns a job to execute the given closure periodically, at a specified fixed interval." – Masklinn