SingleTimer.cpp 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. #include "stdafx.h"
  2. #include "SingleTimer.h"
  3. UINT WINAPI TimerWaitThread(LPVOID pM);
  4. HANDLE hWaitEvent = NULL;
  5. SingleTimer::SingleTimer()
  6. {
  7. m_isRunning = false;
  8. hWaitEvent = CreateEventA(NULL, TRUE, FALSE, 0); //手动设置,初始状态为无信号
  9. m_hWaitThread = NULL;
  10. m_waitMS = 3000;
  11. }
  12. SingleTimer:: ~SingleTimer()
  13. {
  14. if (hWaitEvent)
  15. {
  16. CloseHandle(hWaitEvent);
  17. hWaitEvent = NULL;
  18. }
  19. if (m_hWaitThread)
  20. {
  21. WaitForSingleObject(m_hWaitThread, INFINITE); //等待线程执行完
  22. CloseHandle(m_hWaitThread);
  23. m_hWaitThread = NULL;
  24. }
  25. }
  26. void SingleTimer::start()
  27. {
  28. if(isRunning())
  29. return;
  30. m_isRunning = TRUE;
  31. m_hWaitThread = (HANDLE)_beginthreadex(NULL, 0, TimerWaitThread, this, 0, NULL);
  32. }
  33. void SingleTimer::stop()
  34. {
  35. m_isRunning = FALSE;
  36. }
  37. bool SingleTimer::isRunning() const
  38. {
  39. return m_isRunning;
  40. }
  41. void SingleTimer::setWaitTime(int wTime)
  42. {
  43. m_waitMS = wTime;
  44. }
  45. int SingleTimer::waitTime() const
  46. {
  47. return m_waitMS;
  48. }
  49. //等待线程
  50. UINT WINAPI TimerWaitThread(LPVOID pM)
  51. {
  52. SingleTimer *timer = (SingleTimer*)pM;
  53. DWORD dwRet = WaitForSingleObject(hWaitEvent, timer->waitTime()); //挂起线程
  54. timer->stop();
  55. return 0;
  56. }