timer.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  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)*1000;
  36. it.it_interval.tv_sec = t2/1000; //��ʱ�����Ϊ0�룬��ʾֻ����һ��
  37. it.it_interval.tv_nsec = (t2%1000)*1000;
  38. r = timer_settime(h->tid, 0, &it, NULL);
  39. if(r<0) {
  40. return -1;
  41. }
  42. return 0;
  43. }
  44. int timer_start(int t1, int t2, int times, timer_fn_t fn, void *arg)
  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 = times;
  62. h->fn = fn;
  63. h->arg = arg;
  64. h->inited = 1;
  65. r = set_time(h, t1, t2);
  66. if(r<0) {
  67. timer_delete(h->tid);
  68. free(h); return -1;
  69. }
  70. return (int)h;
  71. }
  72. int timer_setup(int h, int t1, int t2)
  73. {
  74. int r;
  75. timer_handle_t *th=(timer_handle_t*)h;
  76. if(!th || !th->inited) {
  77. return -1;
  78. }
  79. return set_time(th, t1, t2);
  80. }
  81. int timer_stop(int h)
  82. {
  83. int r;
  84. timer_handle_t *th=(timer_handle_t*)h;
  85. if(!th || !th->inited) {
  86. return -1;
  87. }
  88. r = timer_delete(th->tid);
  89. th->inited = 0;
  90. free(th);
  91. return r;
  92. }