How can i terminate a tokio task even if its not finished

Hello everyone, i did spawn a couple of tasks inside a runtime,

runtime.block_on(async move {
    tokio::spawn(...);
    tokio::spawn(...);

    // do the work
});

i would like the runtime to shutdown properly when do the work is done even if the spawned tasks did not finish.

tokio::spawn is conceptually same as thread::spawn. Like threads, force shutdown tasks externally is not supported. But you can wrap the inner future itself with futures::future::select with another future that can accept external signal. If the signalling future completes, the other future will be dropped and should cancel all its pending tasks.

let (sender, receiver) = tokio::sync::oneshot::channel();
tokio::spawn(futures::future::select(get_task(), receiver.map_err(drop)));
sender.send(()); // this will cancel the task
1 Like

You can use the Abortable type to make that wrapper easily: https://docs.rs/futures/0.3.4/futures/future/struct.Abortable.html

2 Likes

Note that futures-util provides a remote_handle, which functions very similar to the already-mentioned abortable. The difference is whether killing the tasks happen when abort() is called, or when the remote is dropped, and you might prefer the remote as that also kills the tasks if a panic happens in the master task.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.