timerqueue.h 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. #ifndef TIMERQUEUE_H
  2. #define TIMERQUEUE_H
  3. #pragma once
  4. #include "config.h"
  5. #ifdef __cplusplus
  6. extern "C" {
  7. #endif
  8. typedef struct timer_entry timer_entry;
  9. typedef struct timer_queue_s timer_queue_t;
  10. typedef void (*timerqueue_callback)(timer_queue_t *q, timer_entry *timer, int err);
  11. struct timer_entry
  12. {
  13. /**
  14. * User data to be associated with this entry.
  15. * Applications normally will put the instance of object that
  16. * owns the timer entry in this field.
  17. */
  18. void *user_data;
  19. /**
  20. * Arbitrary ID assigned by the user/owner of this entry.
  21. * Applications can use this ID to distinguish multiple
  22. * timer entries that share the same callback and user_data.
  23. */
  24. int id;
  25. /**
  26. * Callback to be called when the timer expires.
  27. */
  28. timerqueue_callback cb;
  29. /**
  30. * Internal usage only, user dont use it
  31. */
  32. void *_private[4];
  33. };
  34. /** timer queue implemented by sorted list */
  35. TOOLKIT_API int timer_sortedlist_create(timer_queue_t **p_q);
  36. /** timer queue implemented by heap */
  37. TOOLKIT_API int timer_heap_create(timer_queue_t **p_q);
  38. /** timer queue implemented by wheel */
  39. TOOLKIT_API int timer_wheel_create(int num_wheel, int wheel_time, timer_queue_t **p_q);
  40. /**
  41. * destroy timer queue
  42. */
  43. TOOLKIT_API void timer_queue_destroy(timer_queue_t *q);
  44. /**
  45. * set timer
  46. * @param delay delay time from now, in milliseconds, zero means due immediately
  47. */
  48. TOOLKIT_API int timer_queue_schedule(timer_queue_t *q, timer_entry *entry, unsigned int delay);
  49. /**
  50. * cancel timer
  51. */
  52. TOOLKIT_API int timer_queue_cancel(timer_queue_t *q, timer_entry *entry, int cancel);
  53. /**
  54. * get timer count in the heap
  55. */
  56. TOOLKIT_API int timer_queue_get_count(timer_queue_t *q);
  57. /**
  58. * poll the timer heap
  59. * @param next_delay next delay in milliseconds, can be null, if next_delay == -1, no timer in the heap
  60. * @return the number of triggered timers
  61. */
  62. TOOLKIT_API int timer_queue_poll(timer_queue_t *q, int *next_delay);
  63. /**
  64. * poll only one timer in the time heap
  65. * @param p_entry pointer to the timer which is expired, if not will be NULL
  66. * @param next_delay next delay in milliseconds, can be null, if next_delay == -1, no timer in the heap
  67. * @return the number of triggered timers
  68. */
  69. TOOLKIT_API int timer_queue_poll_one(timer_queue_t *q, timer_entry **p_entry, int *next_delay);
  70. #ifdef __cplusplus
  71. } // extern "C" {
  72. #endif
  73. #endif // TIMERQUEUE_H