struct uv_timer_t

UV_EXTERN int uv_timer_init(uv_loop_t*, uv_timer_t* handle);
UV_EXTERN int uv_timer_start(uv_timer_t* handle,
                             uv_timer_cb cb,
                             uint64_t timeout,
                             uint64_t repeat);
UV_EXTERN int uv_timer_stop(uv_timer_t* handle);
UV_EXTERN int uv_timer_again(uv_timer_t* handle);
UV_EXTERN void uv_timer_set_repeat(uv_timer_t* handle, uint64_t repeat);
UV_EXTERN uint64_t uv_timer_get_repeat(const uv_timer_t* handle);

Notes: uv_timer_t is a subclass of uv_handle_t.

Run timers

Reference to struct uv_loop_t::timer_heap.

void uv__run_timers(uv_loop_t* loop) {
  struct heap_node* heap_node;
  uv_timer_t* handle;

  for (;;) {
    heap_node = heap_min((struct heap*) &loop->timer_heap);
    if (heap_node == NULL)

    handle = container_of(heap_node, uv_timer_t, heap_node);
    if (handle->timeout > loop->time)



  • loop->timer_heap is the root of a binary min heap - struct heap*. The usual properties hold: the root is the lowest element in the set, the height of the tree is at most log2(nodes) and it’s always a complete binary tree.


Reference to struct uv_loop_t::time.

UV_UNUSED(static void uv__update_time(uv_loop_t* loop)) {
  /* Use a fast time source if available.  We only need millisecond precision.
  loop->time = uv__hrtime(UV_CLOCK_FAST) / 1000000;

uint64_t uv_now(const uv_loop_t* loop) {
  return loop->time;

/* Get the next timeout from heap timer_heap. */
int uv__next_timeout(const uv_loop_t* loop) {
  const struct heap_node* heap_node;
  const uv_timer_t* handle;
  uint64_t diff;

  heap_node = heap_min((const struct heap*) &loop->timer_heap);
  if (heap_node == NULL)
    return -1; /* block indefinitely */

  handle = container_of(heap_node, const uv_timer_t, heap_node);
  if (handle->timeout <= loop->time)
    return 0;

  diff = handle->timeout - loop->time;
  if (diff > INT_MAX)
    diff = INT_MAX;

  return diff;

/* Allow timeout milliseconds to run in this function. 
 * Timeout, it should be returned. */
void uv__io_poll(uv_loop_t* loop, int timeout); /* in milliseconds or -1 */