Search code examples
asynchronousrustrust-tokio

How to find the number of active tokio tasks?


I would like to get the count of active running tokio tasks. In python, I can use len(asyncio.all_tasks()) which returns the unfinished tasks for the current running loop. I would like to know any equivalent in tokio.

Here is a sample code:

use std::time::Duration;
use tokio; // 1.24.1
use tokio::time::sleep;

fn active_tasks() -> usize {
    todo!("get active task somehow")
}

#[tokio::main]
async fn main() {
    tokio::spawn(async { sleep(Duration::from_secs(5)).await });
    tokio::spawn(async { sleep(Duration::from_secs(1)).await });
    tokio::spawn(async { sleep(Duration::from_secs(3)).await });

    println!("t = 0, running = {}", active_tasks());

    sleep(Duration::from_secs(2)).await;
    println!("t = 2, running = {}", active_tasks());

    sleep(Duration::from_secs(4)).await;
    println!("t = 6, running = {}", active_tasks());
}

I expect the output of the above program to print number of active task, since main itself is a tokio task, I would not be surprised to find the following output:

t = 0, running = 4
t = 2, running = 3
t = 6, running = 1

active_tasks() can be an async function if required.


Solution

  • With tokio 1.29 RuntimeMetrics now has a method active_task_count() which returns the number of active tokio tasks.

    use tokio::runtime::Handle;
    
    #[tokio::main]
    async fn main() {
        let metrics = Handle::current().metrics();
    
        let n = metrics.active_tasks_count();
        println!("Runtime has {} active tasks", n);
    }