timer.c 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  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. int last=0;
  18. if(h->times_max>0) {
  19. if(h->times<h->times_max) {
  20. h->times++;
  21. }
  22. if(h->times==h->times_max) {
  23. last = 1;
  24. }
  25. h->fn(h->arg, last);
  26. }
  27. else {
  28. h->fn(h->arg, 0);
  29. }
  30. }
  31. }
  32. static int set_time(timer_handle_t *h, int t1, int t2)
  33. {
  34. int r;
  35. struct itimerspec it;
  36. it.it_value.tv_sec = t1/1000; //��ʱ����ʼ����ʱ��
  37. it.it_value.tv_nsec = (t1%1000)*1000;
  38. it.it_interval.tv_sec = t2/1000; //��ʱ�����Ϊ0�룬��ʾֻ����һ��
  39. it.it_interval.tv_nsec = (t2%1000)*1000;
  40. r = timer_settime(h->tid, 0, &it, NULL);
  41. if(r<0) {
  42. return -1;
  43. }
  44. return 0;
  45. }
  46. int timer_start(int t1, int t2, int times, timer_fn_t fn, void *arg)
  47. {
  48. int r;
  49. struct sigevent sev;
  50. timer_handle_t *h=(timer_handle_t*)malloc(sizeof(timer_handle_t));
  51. if(!h) {
  52. return -1;
  53. }
  54. sev.sigev_notify = SIGEV_THREAD; // ֪ͨ����Ϊ�߳�
  55. sev.sigev_notify_function = timer_callback; // �ص�����
  56. sev.sigev_notify_attributes = NULL;
  57. sev.sigev_value.sival_ptr = h; // ���ݸ��ص�����������
  58. r = timer_create(CLOCK_REALTIME, &sev, &h->tid);
  59. if(r<0) {
  60. free(h); return -1;
  61. }
  62. h->times = 0;
  63. h->times_max = times;
  64. h->fn = fn;
  65. h->arg = arg;
  66. h->inited = 1;
  67. r = set_time(h, t1, t2);
  68. if(r<0) {
  69. timer_delete(h->tid);
  70. free(h); return -1;
  71. }
  72. return (int)h;
  73. }
  74. int timer_setup(int h, int t1, int t2)
  75. {
  76. int r;
  77. timer_handle_t *th=(timer_handle_t*)h;
  78. if(!th || !th->inited) {
  79. return -1;
  80. }
  81. return set_time(th, t1, t2);
  82. }
  83. int timer_stop(int h)
  84. {
  85. int r;
  86. timer_handle_t *th=(timer_handle_t*)h;
  87. if(!th || !th->inited) {
  88. return -1;
  89. }
  90. r = timer_delete(th->tid);
  91. th->inited = 0;
  92. free(th);
  93. return r;
  94. }