C++ 毫秒定时器

  1. /*******************************************************************************
  2. *LRTimer.h*
  3. **
  4. *WrittenbyMaxGurdziel2005underGNUGeneralPublicLicense*
  5. *contactme:max[at]remoteSOS[dot]com*
  6. **
  7. *LRTimerisalowresolutiontimerclasswithowntimingthread.Itallows*
  8. *anexternalcallbackfunctiontobesuppliedthatwillbecalledin*
  9. *pre-definedtimeintervals.*
  10. *Thesmallesttimerintervalyoucanuseis1ms.*
  11. **
  12. *Testedwithgccmingw&VisualC++6.0underWindowsXPHomeandPro*
  13. **
  14. **
  15. *LRTimertimer;//defineLRTimerobject*
  16. *timer.setInterval(100);//setintervalof100ms*
  17. *timer.setCallbackProc(&myCallbackFunction,0);//setcallbackfunction*
  18. *//it'sprototypeis:*
  19. *//voidmyCallbackFunction(void*pParam);*
  20. **
  21. *timer.start();//startthetimer*
  22. *....*
  23. *timer.stop();//stopsthetimer*
  24. *....*
  25. *timer.start(200);//startstimerwithnewinterval*
  26. **
  27. **
  28. *Examplecode:*
  29. *CopyandpastebelowsamplecodetotestLRTimer*
  30. **
  31. ________________________________________________________________________________
  32. #include<stdlib.h>
  33. #include"LRTimer.h"
  34. //definecallbackfunction
  35. //
  36. staticvoidmyCallback(void*data)
  37. {
  38. staticDWORDcnt=0;
  39. charc;
  40. cnt++;
  41. switch(cnt%4)
  42. {
  43. case0:c='|';break;
  44. case1:c='/';break;
  45. case2:c='-';break;
  46. case3:c='//';
  47. }
  48. printf("/b%c",c);
  49. }
  50. intmain(intargc,char*argv[])
  51. {
  52. LRTimerlrt;
  53. lrt.setCallbackProc(&myCallback,NULL);//setthecallbackfunctionbyreference
  54. lrt.setInterval(50);//setdelayintervalinmiliseconds
  55. lrt.start();//startthetimer
  56. getchar();//letitrunforawhile-pressEnter
  57. lrt.stop();//stopthetimer
  58. getchar();//waittoshowit'sstopped-Enter
  59. lrt.start(200);//startwithdifferentdelay
  60. getchar();
  61. lrt.stop();
  62. system("PAUSE");
  63. return0;
  64. }
  65. ________________________________________________________________________________
  66. **
  67. *Permissiontouse,copy,modify,anddistributethissoftwareandits*
  68. *documentationunderthetermsoftheGNUGeneralPublicLicenseishereby*
  69. *granted.Norepresentationsaremadeaboutthesuitabilityofthissoftware*
  70. *foranypurpose.Itisprovided"asis"withoutexpressorimpliedwarranty.*
  71. *Seehttp://www.gnu.org/copyleft/gpl.htmlformoredetails.*
  72. **
  73. *AllIaskisthatifyouuseLRTimerinyourprojectretainthe*
  74. *copyrightnotice.Ifyouhaveanycommentsandsuggestionspleaseemailme*
  75. *max[at]remoteSOS[dot]com*
  76. **
  77. *******************************************************************************/
  78. #ifndefLRTIMER_H__
  79. #defineLRTIMER_H__
  80. #ifndef_WIN32_WINNT
  81. #define_WIN32_WINNT0x0500
  82. #endif
  83. //compilewith:/MT/D"_X86_"/c
  84. //processor:x86
  85. #include<windows.h>
  86. #include<process.h>/*_beginthread,_endthread*/
  87. #include<stdio.h>
  88. #include<assert.h>
  89. //defineasecondintermsof100ns-usedwithwaitabletimerAPI
  90. #define_SECOND10000
  91. typedefVOID(*LRTCallbackEventProc)(VOID*);
  92. classLRTimer
  93. {
  94. public:
  95. //defaultconstructorwith1secondinterval
  96. LRTimer(DWORDdwInterval=1000);
  97. //defaultdestructor
  98. ~LRTimer();
  99. //startstimerbycreatingnewthread.intervalmustbesetearlier
  100. VOIDstart();
  101. //startstimerwithgivenintervalinmiliseconds
  102. VOIDstart(DWORD_interval_ms);
  103. //stopsthetimer
  104. VOIDstop();
  105. //setstimeintervalinmiliseconds
  106. VOIDsetInterval(DWORD_interval_ms);
  107. //returnstimeintervalinms
  108. DWORDgetInterval();
  109. //setsfunctionthatwillbecalledontimeexpiration
  110. VOIDsetCallbackProc(LRTCallbackEventProcpcbEventProc,VOID*pcbParam);
  111. //returnstrueifLRtimeriscurrentlyrunning
  112. BOOLisRunning();
  113. //ItshouldbeusediftheworkerclasswilluseCRTfunctions
  114. staticHANDLECrtCreateThread(LPSECURITY_ATTRIBUTESlpsa,DWORDdwStackSize,LPTHREAD_START_ROUTINEpfnThreadProc,void*pvParam,DWORDdwCreationFlags,DWORD*pdwThreadId)throw()
  115. {
  116. //sanitycheckforpdwThreadId
  117. assert(sizeof(DWORD)==sizeof(unsignedint));
  118. //_beginthreadexcallsCreateThreadwhichwillsetthelasterrorvaluebeforeitreturns
  119. return(HANDLE)_beginthreadex(lpsa,dwStackSize,(unsignedint(__stdcall*)(void*))pfnThreadProc,pvParam,dwCreationFlags,(unsignedint*)pdwThreadId);
  120. }
  121. private:
  122. DWORDm_dwInterval;//intervalbetweenalarms
  123. LRTCallbackEventProcm_pCallback;//pointertousercallbackfunction
  124. VOID*m_pcbParam;//pointertousercallbackparameter
  125. BOOLm_bRunning;//timerrunningstate
  126. HANDLEm_hTimerThread;//handletotimerthread
  127. DWORDm_iID;//timerthreadid-addedforcompatibilitywithWin95/98
  128. //timerclockingtreadruntine
  129. virtualDWORDWINAPItimerThread();
  130. //wrappertothreadruntinesoitcanbeusedwithinaclass
  131. staticDWORDWINAPItimerThreadAdapter(PVOID_this)
  132. {
  133. return((LRTimer*)_this)->timerThread();
  134. }
  135. //timercallbackAPCprocedurecalledwhentimerissignaled
  136. virtualVOIDCALLBACKTimerAPCProc(LPVOID,DWORD,DWORD);
  137. //wrappertocallbackAPCproceduresoitcanbeusedwithinaclass
  138. staticVOIDCALLBACKTimerAPCProcAdapter(PVOID_this,DWORDa1=0,DWORDa2=0)
  139. {
  140. ((LRTimer*)_this)->TimerAPCProc(NULL,a1,a2);
  141. }
  142. };
  143. #endif

  1. /*******************************************************************************
  2. *LRTimer.cpp*
  3. **
  4. *WrittenbyMaxGurdziel2005underGNUGeneralPublicLicense*
  5. *contactme:max[at]remoteSOS[dot]com*
  6. **
  7. *LRTimerisalowresolutiontimerclasswithowntimingthread.Itallows*
  8. *anexternalcallbackfunctiontobesuppliedthatwillbecalledin*
  9. *pre-definedtimeintervals.Thesmallesttimerintervalyoucanuseis1ms.*
  10. **
  11. *Seeheaderfileformoreinfo,usageinformationandexample*
  12. **
  13. **
  14. **
  15. *Permissiontouse,copy,modify,anddistributethissoftwareandits*
  16. *documentationunderthetermsoftheGNUGeneralPublicLicenseishereby*
  17. *granted.Norepresentationsaremadeaboutthesuitabilityofthissoftware*
  18. *foranypurpose.Itisprovided"asis"withoutexpressorimpliedwarranty.*
  19. *Seehttp://www.gnu.org/copyleft/gpl.htmlformoredetails.*
  20. **
  21. *AllIaskisthatifyouuseLRTimerinyourprojectyouretainthe*
  22. *copyrightnotice.Ifyouhaveanycommentsandsuggestionspleaseemailme*
  23. *max[at]remoteSOS[dot]com*
  24. **
  25. *2008-6-23ModifiedbyZhangLiang*
  26. **
  27. *******************************************************************************/
  28. #include"stdafx.h"
  29. #include"LRTimer.h"
  30. #ifndef_WIN32_WINNT
  31. #define_WIN32_WINNT0x0500
  32. #endif
  33. LRTimer::LRTimer(DWORDdwInterval):
  34. m_dwInterval(dwInterval),
  35. m_bRunning(FALSE),
  36. m_pCallback(NULL),
  37. m_pcbParam(NULL),
  38. m_hTimerThread(0)
  39. {}
  40. LRTimer::~LRTimer()
  41. {}
  42. VOIDCALLBACKLRTimer::TimerAPCProc(LPVOID,DWORD,DWORD)
  43. {
  44. //callcustomcallbackfunction
  45. if(NULL!=m_pCallback)
  46. (*m_pCallback)(m_pcbParam);
  47. #ifdef_DEBUG
  48. else
  49. printf("Nocallbackfunctionset/n");
  50. #endif
  51. }
  52. DWORDWINAPILRTimer::timerThread()
  53. {
  54. HANDLEhTimer;
  55. BOOLbSuccess;
  56. LARGE_INTEGERliDueTime;
  57. CHARszError[255];
  58. CHARszTimerName[16];
  59. sprintf_s(szTimerName,"LRT_%x",(DWORD)(DWORD_PTR)this);
  60. if(hTimer=CreateWaitableTimerA(NULL,FALSE,szTimerName))
  61. liDueTime.QuadPart=-(LONGLONG)m_dwInterval*_SECOND;
  62. bSuccess=SetWaitableTimer(
  63. hTimer,//Handletothetimerobject
  64. &liDueTime,//Whentimerwillbecomesignaledfirsttime
  65. m_dwInterval,//Periodictimerinterval
  66. TimerAPCProcAdapter,//Completionroutine
  67. this,//Argumenttothecompletionroutine
  68. FALSE);//Donotrestoreasuspendedsystem
  69. if(bSuccess){
  70. while(m_bRunning)
  71. SleepEx(1,TRUE);//SleepEx(0,TRUE)consumes100%CPUusage
  72. CancelWaitableTimer(hTimer);
  73. }else{
  74. wsprintfA(szError,"SetWaitableTimerfailedwithError%d.",GetLastError());
  75. #ifdef_DEBUG
  76. MessageBoxA(NULL,szError,"Error",MB_ICONEXCLAMATION);
  77. #endif
  78. return1;
  79. }
  80. CloseHandle(hTimer);
  81. return0;
  82. }
  83. VOIDLRTimer::start()
  84. {
  85. m_bRunning=TRUE;
  86. if(m_hTimerThread!=0)
  87. stop();
  88. #ifndef_INC_CRTDEFS
  89. m_hTimerThread=CreateThread(NULL,0,timerThreadAdapter,this,0,&m_iID);
  90. #else
  91. m_hTimerThread=CrtCreateThread(NULL,0,timerThreadAdapter,this,0,&m_iID);
  92. #endif
  93. if(m_hTimerThread==NULL)
  94. {
  95. #ifdef_DEBUG
  96. printf("CreateThreadfailed(%d)/n",GetLastError());
  97. #endif
  98. return;
  99. }
  100. }
  101. VOIDLRTimer::start(DWORD_interval_ms)
  102. {
  103. setInterval(_interval_ms);
  104. start();
  105. }
  106. VOIDLRTimer::stop()
  107. {
  108. m_bRunning=FALSE;
  109. CloseHandle(m_hTimerThread);
  110. m_hTimerThread=0;
  111. }
  112. VOIDLRTimer::setInterval(DWORD_interval_ms)
  113. {
  114. m_dwInterval=_interval_ms;
  115. }
  116. DWORDLRTimer::getInterval()
  117. {
  118. returnm_dwInterval;
  119. }
  120. VOIDLRTimer::setCallbackProc(LRTCallbackEventProcpcbEventProc,VOID*pcbParam)
  121. {
  122. m_pCallback=pcbEventProc;
  123. m_pcbParam=pcbParam;
  124. }
  125. BOOLLRTimer::isRunning()
  126. {
  127. returnm_bRunning;
  128. }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值