Skip to content

Is it possible create background task wich should do something. #2644

Answered by Darksonn
heckad asked this question in General
Discussion options

You must be logged in to vote

The easiest way to kill the task when you exit the scope is to use remote_handle from the futures-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 in db.rs.

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 d…

Replies: 1 comment 3 replies

Comment options

You must be logged in to vote
3 replies
@heckad
Comment options

@Darksonn
Comment options

@heckad
Comment options

Answer selected by heckad
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
2 participants