-
I want to print an app state every minute. To solve this problem, I need to do something that will work in the background and when I exit from a scope this background task should stop.
How to do this or maybe we have a library yet? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
The easiest way to kill the task when you exit the scope is to use use tokio::time::{self, Duration};
async fn some_func(state: AppState) {
let (job, _handle) = futures_util::future::FutureExt::remote_handle(monitor(state.clone()));
tokio::spawn(job);
// do stuff
// _handle goes out of scope here, which kills the task
}
async fn monitor(state: AppState) {
let mut interval = time::interval(Duration::from_secs(60)); // or delay_for
loop {
interval.tick().await;
info!("App state is {:?}", state);
}
} As an alternative to As an alternative, you can use the use tokio::time::{interval, Duration};
async fn some_func(state1: AppState) {
let state2 = state1.clone();
tokio::select! {
_ = do_stuff(state1) => {},
_ = monitor(state2) => {},
}
}
async fn do_stuff(state: AppState) {
// ...
}
async fn monitor(state: AppState) {
let mut interval = interval(Duration::from_secs(60));
loop {
interval.tick().await;
info!("App state is {:?}", state);
}
} |
Beta Was this translation helpful? Give feedback.
The easiest way to kill the task when you exit the scope is to use
remote_handle
from thefutures-util
crate. Note that this requires your state to be share-able in some manner. If your state is currently not share-able, the mini-redis example has an illustration of a common way of sharing mutable state indb.rs
.