timer.c 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  1. #include <time.h>
  2. #include <signal.h>
  3. #include <stdlib.h>
  4. #include "timer.h"
  5. typedef struct {
  6. timer_t tid;
  7. int times;
  8. int times_max;
  9. timer_fn_t fn;
  10. void *arg;
  11. int inited;
  12. }timer_handle_t;
  13. static void timer_callback(sigval_t sv)
  14. {
  15. timer_handle_t *h=(timer_handle_t*)sv.sival_ptr;
  16. if(h->fn) {
  17. if(h->times_max>0 && h->times<h->times_max) {
  18. int last=0;
  19. h->times++;
  20. if(h->times==h->times_max) {
  21. last = 1;
  22. }
  23. h->fn(h->arg, last);
  24. }
  25. else {
  26. h->fn(h->arg, 0);
  27. }
  28. }
  29. }
  30. static int set_time(timer_handle_t *h, int t1, int t2)
  31. {
  32. int r;
  33. struct itimerspec it;
  34. it.it_value.tv_sec = t1/1000; //��ʱ����ʼ����ʱ��
  35. it.it_value.tv_nsec = (t1%1000)*1000000;
  36. it.it_interval.tv_sec = t2/1000; //��ʱ�����Ϊ0�룬��ʾֻ����һ��
  37. it.it_interval.tv_nsec = (t2%1000)*1000000;
  38. r = timer_settime(h->tid, 0, &it, NULL);
  39. if(r<0) {
  40. return -1;
  41. }
  42. return 0;
  43. }
  44. int timer_init(void)
  45. {
  46. int r;
  47. struct sigevent sev;
  48. timer_handle_t *h=(timer_handle_t*)malloc(sizeof(timer_handle_t));
  49. if(!h) {
  50. return -1;
  51. }
  52. sev.sigev_notify = SIGEV_THREAD; // ֪ͨ����Ϊ�߳�
  53. sev.sigev_notify_function = timer_callback; // �ص�����
  54. sev.sigev_notify_attributes = NULL;
  55. sev.sigev_value.sival_ptr = h; // ���ݸ��ص�����������
  56. r = timer_create(CLOCK_REALTIME, &sev, &h->tid);
  57. if(r<0) {
  58. free(h); return -1;
  59. }
  60. h->times = 0;
  61. h->times_max = 0;
  62. h->fn = NULL;
  63. h->arg = NULL;
  64. h->inited = 1;
  65. return (int)h;
  66. }
  67. int timer_deinit(int h)
  68. {
  69. int r;
  70. timer_handle_t *th=(timer_handle_t*)h;
  71. if(h==-1 || !th->inited) {
  72. return -1;
  73. }
  74. r = timer_delete(th->tid);
  75. th->inited = 0;
  76. free(th);
  77. return r;
  78. }
  79. int timer_start(int h, int t, int times, timer_fn_t fn, void *arg)
  80. {
  81. int r;
  82. timer_handle_t *th=(timer_handle_t*)h;
  83. if(h==-1 || !th->inited) {
  84. return -1;
  85. }
  86. set_time(th, 0, 0);
  87. th->times = 0;
  88. th->times_max = times;
  89. th->fn = fn;
  90. th->arg = arg;
  91. return set_time(th, 1000, t);
  92. }
  93. int timer_stop(int h)
  94. {
  95. int r;
  96. timer_handle_t *th=(timer_handle_t*)h;
  97. if(h==-1 || !th->inited) {
  98. return -1;
  99. }
  100. r = set_time(th, 0, 0);
  101. return r;
  102. }