Refreshing items in a db with a &'static connection

Hi, I would like to do something like this (periodically refresh available currencies in a database from an API)

pub async fn start_refresher(db: &Db) {
    api::AvailableCurrenciesApi
        .refresh(Data(db))
        .await
        .map_err(|err| error!("{}", err));

    let ticker = crossbeam_channel::tick(Duration::from_secs(6 * 3600));

    tokio::task::spawn(async move {
        loop {
            let owned_ticker = ticker.clone();

            tokio::task::spawn_blocking(move || {
                owned_ticker.recv().map_err(|err| warn!("{}", err))
            });

            api::AvailableCurrenciesApi
                .refresh(Data(db))
                .await
                .map_err(|err| warn!("{}", err));
        }
    });
}

I'm using this function to generate the connection:

async fn db_connect(db_url: &str) -> DatabaseConnection {
    sea_orm::Database::connect(db_url)
        .await
        .expect("Could not connect to the database")
}

It seems as if I need to have the connection as &'static because of the tokio::task::spawn. I'm using Poem and SeaORM. I would appreciate any help.

The various database types can often be cloned, resulting in another handle to the same database. You typically solve this kind of thing by making a clone and passing the clone to the spawned task.

You should not attempt to create a 'static reference.

I'm also quite puzzled by your use of the crossbeam ticker. You are not actually waiting for those spawn_blocking tasks. Are you perhaps looking for tokio::time::Interval?

1 Like