Is there an idiomatic way to periodically execute a method on the app's state? #768
-
My use-case for this is periodically removing unused entries from a SQL database. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
The way I'd approach this would be to create a copy of // Create an instance of your `State`
let state = State::new();
// Clone your `State` and pass it into a task where we'll perform the periodic cleanup
let cleanup_state = state.clone();
let handle = task::spawn(async move {
while let Some(_) = async_std::task::sleep(Duration::from_secs(10)) {
// SQL cleanup here
cleanup_state.db().cleanup().await?;
}
Ok(())
});
// Create the tide app, and listen on a port
// If either the DB cleanup or tide server fail, the application will exit.
let mut app = tide::with_state(state);
app.at("/").get(|_| async { Ok("hello world") });
app.listen("localhost:8080").try_race(handle)?; // using async-std's `Future::try_race` Tide currently does not handle any application lifecycle things such as restarts, wait groups, and the like. We expect people to use supporting libraries for that. Our hope is that by not building everything directly into Tide we can enable composition and competition, which in turn reduces the burden on us to build solutions for everything, and enables a composable async ecosystem to emerge. I hope this answers your question! |
Beta Was this translation helpful? Give feedback.
The way I'd approach this would be to create a copy of
State
on creation and move it into a separate task which can then indeed operate on a loop.State
is already required to beClone + Send
, so that shouldn't be a problem. I'd imagine this would look something like this: