Answers for "force tokio task to end"

0

force tokio task to end

/*
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
Posted by: Guest on October-26-2020

Browse Popular Code Answers by Language