Get a count of (active) timers in a Node.js event loop

Is there a way to make a call in Node.js to determine the number of timers in the event loop queue? I have a library with a lot of timeouts, and instead of tracking them myself using some kind of internal accounting system, it would be nice if I could just ask V8 or Libuv or something else how many timers are there .

Is it possible?

+6
source share
1 answer

It would be nice if I could just ask V8 or Libuv or something else

You cannot directly ask libuv, but it certainly offers a way to find out how many active timers exist.
To do this, you can call uv_walk with a valid loop to get all active descriptors. You can then check each descriptor with the given callback and count those for which the type data element (which has the uv_handle_type type) is equal to UV_TIMER .
The result is the number of active timers.

See the descriptor data structure for more details.


As a trivial example, consider the following structure:

 struct Counter { static int count; static void callback(uv_handle_t* handle, void*) { if(handle.type == uv_handle_type::UV_TIMER) count++; } }; 

You can use it as follows:

 Counter::count = 0; uv_walk(my_loop_ptr, &Counter::callback); // Counter::count indicates how many active timers are running on the loop 

Of course, this is not production-ready code. In any case, I hope this gives an idea of ​​the proposed solution.


See here for libuv documentation.

+2
source

Source: https://habr.com/ru/post/1013561/


All Articles