Browse Source Download (without any required ccan dependencies)

Module:

timer

Summary:

efficient implementation of rarely-expiring timers.

Author:

Rusty Russell <rusty@rustcorp.com.au>

Dependencies:

Description:

This is a lazy implementation of timers: you can add and delete timers very quickly, and they are only sorted as their expiry approaches.

This is a common case for timeouts, which must often be set, but rarely expire.

Example:

// Silly example which outputs strings until timers expire.
#include <ccan/timer/timer.h>
#include <ccan/time/time.h>
#include <stdlib.h>
#include <stdio.h>

struct timed_string {
        struct list_node node;
        struct timer timer;
        const char *string;
};

int main(int argc, char *argv[])
{
        struct timers timers;
        struct list_head strings;
        struct list_head expired;
        struct timed_string *s;

        timers_init(&timers, time_now());
        list_head_init(&strings);

        while (argv[1]) {
                s = malloc(sizeof(*s));
                s->string = argv[1];
                timer_add(&timers, &s->timer,
                          timeabs_add(time_now(),
                                      time_from_msec(atol(argv[2]))));
                list_add_tail(&strings, &s->node);
                argv += 2;
        }

        while (!list_empty(&strings)) {
                struct timeabs now = time_now();
                list_for_each(&strings, s, node)
                        printf("%s", s->string);
                timers_expire(&timers, now, &expired);
                while ((s = list_pop(&expired, struct timed_string,
                                     timer.list)) != NULL) {
                        list_del_from(&strings, &s->node);
                        free(s);
                }
        }

        exit(0);
}

License:

LGPL (v2.1 or any later version)