平时创建定时器使用的是WINAPI  SetTimer,不过该函数一般用于有界面的时候。无界面的情况下,可以选择微软提供的CreateWaitableTimer和SetWaitableTimer API。

 

HANDLE WINAPI CreateWaitableTimer(
  _In_opt_  LPSECURITY_ATTRIBUTES lpTimerAttributes,
  _In_      BOOL bManualReset,
  _In_opt_  LPCTSTR lpTimerName
);

BOOL WINAPI SetWaitableTimer(
  _In_      HANDLE hTimer,
  _In_      const LARGE_INTEGER *pDueTime,
  _In_      LONG lPeriod,
  _In_opt_  PTIMERAPCROUTINE pfnCompletionRoutine,
  _In_opt_  LPVOID lpArgToCompletionRoutine,
  _In_      BOOL fResume
);

详细介绍可以查看MSDN( http://msdn.microsoft.com/en-us/library/windows/desktop/ms682492(v=vs.85).aspx )

一、应用实例

我自己在使用的时候,封装了一个类,用来创建了一个线程,并定时调用我提供的函数。类代码如下:

 1 #ifndef APLAYER_TIMERTHREAD_H
 2 #define APLAYER_TIMERTHREAD_H
 3 #include <Windows.h>
 4 class CTimerThread
 5 {
 6 public:
 7     CTimerThread() :
 8         _hThread(NULL), _hEvent(NULL),
 9         _bRunning(false), _nInterval(10)
10     {}
11     ~CTimerThread()
12     {
13         KillTimer();
14     }
15 public:
16     int                        CreateTimer(unsigned int interval, PTIMERAPCROUTINE func, void* lpParam);
17     void                    KillTimer();
18 private:
19     static DWORD WINAPI        timerThread(LPVOID lpParam);
20 
21 private:
22     HANDLE                _hTimer;
23     int                    _nInterval;
24     HANDLE                _hEvent;
25     void*                _lpParam;
26 
27     PTIMERAPCROUTINE    _callbackFunc;
28     HANDLE                _hThread;
29     DWORD                _dwThread;
30     bool                _bRunning;
31 };
32 
33 #endif
TimerThread.h

相关文章:

  • 2022-12-23
  • 2021-08-12
  • 2021-08-27
  • 2022-12-23
  • 2021-10-27
  • 2021-11-09
猜你喜欢
  • 2021-05-21
  • 2022-12-23
  • 2022-12-23
  • 2021-05-31
  • 2022-12-23
  • 2022-02-07
相关资源
相似解决方案