Last active
October 13, 2023 11:35
-
-
Save jow-/56f709408942a84075906675297f279c to your computer and use it in GitHub Desktop.
uloop interval timer example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <inttypes.h> | |
#include <unistd.h> | |
#include <stdlib.h> | |
#include <stdio.h> | |
#include <time.h> | |
#include <libubox/uloop.h> | |
static void timer_cb(struct uloop_timer *utm) | |
{ | |
struct timespec ts; | |
clock_gettime(CLOCK_MONOTONIC, &ts); | |
int64_t t1 = ts.tv_sec * 1000 + ts.tv_nsec / 1000000; | |
printf("[%u:%u] Timer iteration: %" PRIu64 " ... ", | |
(unsigned int)ts.tv_sec, (unsigned int)ts.tv_nsec, | |
utm->expirations); | |
usleep((random() % 1000000)); | |
clock_gettime(CLOCK_MONOTONIC, &ts); | |
int64_t t2 = ts.tv_sec * 1000 + ts.tv_nsec / 1000000; | |
printf("slept %" PRId64 " ms, next run in %" PRId64 " ms\n", | |
t2 - t1, uloop_timer_next(utm)); | |
} | |
int main(int argc, char **argv) | |
{ | |
struct uloop_timer utm = { .cb = timer_cb }; | |
uloop_init(); | |
uloop_timer_set(&utm, 1000); | |
uloop_run(); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ gcc -o test -L. test.c -lubox | |
$ ./test | |
[54530:581458532] Timer iteration: 1 ... slept 289 ms, next run in 710 ms | |
[54531:581453377] Timer iteration: 2 ... slept 931 ms, next run in 69 ms | |
[54532:581447881] Timer iteration: 3 ... slept 693 ms, next run in 307 ms | |
[54533:581454526] Timer iteration: 4 ... slept 637 ms, next run in 362 ms | |
[54534:581452631] Timer iteration: 5 ... slept 748 ms, next run in 252 ms | |
[54535:581452526] Timer iteration: 6 ... slept 238 ms, next run in 761 ms | |
[54536:581451541] Timer iteration: 7 ... slept 885 ms, next run in 114 ms | |
[54537:581452415] Timer iteration: 8 ... slept 761 ms, next run in 239 ms | |
[54538:581454711] Timer iteration: 9 ... slept 517 ms, next run in 483 ms | |
[54539:581451415] Timer iteration: 10 ... slept 641 ms, next run in 358 ms | |
[54540:581452000] Timer iteration: 11 ... slept 202 ms, next run in 797 ms | |
[54541:581451465] Timer iteration: 12 ... slept 490 ms, next run in 509 ms | |
[54542:581453650] Timer iteration: 13 ... slept 369 ms, next run in 631 ms | |
[54543:581453775] Timer iteration: 14 ... slept 520 ms, next run in 479 ms | |
[54544:581452421] Timer iteration: 15 ... slept 898 ms, next run in 102 ms | |
[54545:581451896] Timer iteration: 16 ... slept 514 ms, next run in 485 ms | |
^C |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment