swtimer.c 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. /************************************************************************
  2. * AUTHOR: NiuJiuRu
  3. * FILENAME: swtimer.c
  4. * CONTENT: 定时器
  5. * NOTE:
  6. * HISTORY:
  7. * 1, [2010-09-14] created by NiuJiuRu
  8. ***********************************************************************/
  9. #include "swapi.h"
  10. #include "swmem.h"
  11. #include "swthrd.h"
  12. #include "swtimer.h"
  13. typedef struct
  14. {
  15. // 定时器的名称
  16. char name[32];
  17. // 定时器的间隔时间(ms)
  18. int period;
  19. // 定时器的线程句柄
  20. void *hThrd;
  21. // 定时器的(用户)回调函数
  22. PTimerProc proc;
  23. unsigned long wParam;
  24. unsigned long lParam;
  25. } STimer;
  26. // 匿名定时器计数器
  27. static int s_nameless_timer_counter = 0;
  28. // 定时器的节拍函数(线程回调)
  29. static int TimerProc(unsigned long wParam, unsigned long lParam);
  30. /* 创建定时器(ms), 成功后默认处于暂停状态 */
  31. void *sw_timer_create(const char *name, int period, PTimerProc proc, unsigned long wParam, unsigned long lParam)
  32. {
  33. STimer *t = NULL;
  34. t = (STimer *)sw_heap_malloc(sizeof(STimer));
  35. if(!t) goto ErrorP;
  36. memset(t, 0, sizeof(STimer));
  37. if(name) strncpy(t->name, name, sizeof(t->name)-1);
  38. else snprintf(t->name, sizeof(t->name)-1, "nameless%d timer", s_nameless_timer_counter++);
  39. t->period = period;
  40. t->proc = proc;
  41. t->wParam = wParam; t->lParam = lParam;
  42. t->hThrd = sw_thrd_create(t->name, THREAD_DEFAULT_PRIORITY, THREAD_DEFAULT_STACK_SIZE, TimerProc, (unsigned long)t, 0);
  43. if(!t->hThrd) goto ErrorP;
  44. return t;
  45. ErrorP:
  46. sw_timer_destroy(t, 0);
  47. return NULL;
  48. }
  49. /* 销毁定时器, 超时前尝试安全的销毁, 超时后则强制销毁 */
  50. void sw_timer_destroy(void *hTimer, int timeout)
  51. {
  52. STimer *t = (STimer *)hTimer;
  53. if(!t) return;
  54. if(t->hThrd)
  55. {
  56. sw_thrd_destroy(t->hThrd, timeout); // destroy thread
  57. t->hThrd = NULL;
  58. }
  59. sw_heap_free(t);
  60. }
  61. /* 暂停运行定时器 */
  62. void sw_timer_pause(void *hTimer)
  63. {
  64. STimer *t = (STimer *)hTimer;
  65. if(!t) return;
  66. if(t->hThrd) sw_thrd_pause(t->hThrd);
  67. }
  68. /* 继续运行定时器 */
  69. void sw_timer_resume(void *hTimer)
  70. {
  71. STimer *t = (STimer *)hTimer;
  72. if(!t) return;
  73. if(t->hThrd) sw_thrd_resume(t->hThrd);
  74. }
  75. /* 设置定时器的节拍时间(ms) */
  76. void sw_timer_setPeriod(void *hTimer, int period)
  77. {
  78. STimer *t = (STimer *)hTimer;
  79. if(!t) return;
  80. t->period = period;
  81. }
  82. // 定时器的节拍函数
  83. static int TimerProc(unsigned long wParam, unsigned long lParam)
  84. {
  85. STimer *t = (STimer *)wParam;
  86. if(!sw_thrd_isAlive(t->hThrd)) return -1;
  87. if(t->proc) t->proc(t->wParam, t->lParam); // 执行定时器的节拍回调函数
  88. return t->period;
  89. }