Actix-Web: Run service every 10 seconds
Asked Answered
F

2

8

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!

Farlay answered 23/9, 2020 at 11:9 Comment(2)
Use actix::spawn to start a task that uses tokio::time::delay_for in a loop to wait for 10s and execute the ping?Bivins
There's also a run_interval which "Spawns a job to execute the given closure periodically, at a specified fixed interval."Romina
E
15

See actix_rt::spawn and actix_rt::time::interval.

Here is an example:

spawn(async move {
    let mut interval = time::interval(Duration::from_secs(10));
    loop {
        interval.tick().await;
        // do something
    }
});
Eulogize answered 23/9, 2020 at 12:54 Comment(0)
A
0
#[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!");
    }

}

This works but only thing being it wont reurn http resposnse to caller

Algonquian answered 25/3, 2021 at 18:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.