How to kill the task with loop?

   let mut hb_task = tokio::spawn(async move {
        let time = Duration::from_secs(1);
        loop {
            park_timeout(time);
            //do sth
        }
    });

I try hb_task.abort() but does't work.

also try

    let mut is_exit = Arc::new(false);
    let is_exit_task = is_exit.clone();

    let mut hb_task = tokio::spawn(async move {
        let time = Duration::from_secs(1);
        loop {
            park_timeout(time);
            let _ = tx_hb.send("hb".to_owned());
            let v = is_exit_task.clone();
            println!("send hb? {}", v);
            if v == true {
                break;
            }
        }
    });
    let v = Arc::get_mut(&mut is_exit);
    match v {
        Some(v) => *v = false,
        None => println!("is none"),
    }

But prints "is none", and nothing changed.

Thank you!

If this is std::thread::park_timeout, you’re doing a blocking call in an async task.

A (potentially infinite) loop without any .await points is problematic in async code. Try including a task::yield_now().await; in the loop.

Alternatively, you could just spawn a thread instead of using async.

Also, you’re ignoring the errors from the .send call to whatever kind of channel you’re using. Typically, you should not do that, e.g. use unwrap instead, or otherwise terminate on an error. The .send call will fail once all the receivers are dropped, which is often a good way to shut down a worker thread / task.

1 Like

Additionally, this feels like more of an URLO question than IRLO (which is for more language/compiler level questions).

4 Likes

Thank you! According to answer, using tokio::time::sleep(time).await; is a better solution.

            // park_timeout(time);
            tokio::time::sleep(time).await;

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