Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a count of (active) timers in 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 number of timeouts and instead of keeping track of them myself using some sort of internal bookkeeping system, it would be nice if I could just ask V8 or Libuv or whatever, how many timers there are.

Is this possible?

like image 510
Alexander Mills Avatar asked Dec 28 '16 01:12

Alexander Mills


People also ask

What is setImmediate in node JS?

setImmediate() This method is used to break up long running operations and run a callback function immediately after the browser has completed other operations such as events and display updates.

How do I clearTimeout in node JS?

clearTimeout() Method: This method comes under the category of canceling timers and is used to cancel the timeout object created by setTimeout. The setTimeout() method also returns a unique timer id which is passed to clearTimeout to prevent the execution of the functionality registered by setTimeout.

What is process Hrtime?

The process. hrtime() method to measure code execution time which returns array which include current high-resolution real time in a [seconds, nanoseconds].

What is i/o polling in node JS?

In Node. js, I/O often refers to reading/writing files or network operations. Network operations get external information into your application, or send data from your application out to something else.


1 Answers

it would be nice if I could just ask V8 or Libuv or whatever

You cannot directly ask libuv, but it certainly offers a way to know how many active timers are there.
To do that, you can invoke uv_walk with a valid loop to get all the active handles. Then you can check each handle with the given callback and count those for which the data member type (that has type uv_handle_type) is equal to UV_TIMER.
The result is the number of active timers.

See the documentation for further details about the handle data structure.


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 it 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 a production-ready code. Anyway, I hope it gives an idea of the proposed solution.


See here for the libuv documentation.

like image 125
skypjack Avatar answered Oct 04 '22 00:10

skypjack