封装成了一个类,以便很好的进行参数传递使用。
TimerThread.h
-
#pragma once
-
#ifndef APLAYER_TIMERTHREAD_H
-
#define APLAYER_TIMERTHREAD_H
-
#include
-
#include
-
-
class cTimerThread {
-
public:
-
cTimerThread()
-
{
-
}
-
~cTimerThread()
-
{
-
// KillTimer();
-
}
-
int CreateTimer(unsigned int interval, PTIMERAPCROUTINE func, void* lpParam);
-
// void KillTimer();
-
-
public:
-
std::
string name;
-
std::
string job_id;
-
bool _bRunning;
-
private:
-
static DWORD WINAPI timerThread(LPVOID lpParam);
-
HANDLE _hTimer;
-
int _nInterval;
-
HANDLE _hEvent;
-
void* _lpParam;
-
-
PTIMERAPCROUTINE _callbackFunc;
-
HANDLE _hThread;
-
DWORD _dwThread;
-
-
};
-
#endif
TimerThread.cpp
-
#include
-
#include
-
#include "TimerThread.h"
-
#include
-
-
using
namespace
std;
-
-
int a =
0;
-
VOID APIENTRY TimerAPCRoutine(PVOID pvArgToCompletionRoutine, DWORD dwTimerLowValue, DWORD dwTimerHighValue)
-
-
{
-
-
a++;
-
cTimerThread* ctt = (cTimerThread* )pvArgToCompletionRoutine;
-
if (a==
4)
-
{
-
ctt->_bRunning =
false;
-
}
-
std::
cout << a<<
"dio:"<< ctt->name.c_str() <<
std::
endl;
-
-
}
-
-
-
int main()
-
{
-
string li =
"name";
-
string job_id =
"w5";
-
cTimerThread timer_;
-
timer_.job_id = job_id;
-
timer_.name = li;
-
void *lpParam =
NULL;
-
timer_.CreateTimer(
1000, TimerAPCRoutine, lpParam);
-
return
0;
-
}
-
-
-
int cTimerThread::CreateTimer(
unsigned
int interval, PTIMERAPCROUTINE func,
void* lpParam)
-
{
-
_nInterval = interval;
-
_callbackFunc = func;
-
_lpParam = lpParam;
-
_bRunning =
true;
-
std::
thread t1(timerThread,this);
-
t1.join();
//线程执行完自动退出
-
return
0;
-
}
-
-
DWORD WINAPI cTimerThread::timerThread(LPVOID lpParam) {
-
cTimerThread* pThis = (cTimerThread*)lpParam;
-
HANDLE hTimer = CreateWaitableTimer(
NULL, FALSE,
NULL);
-
-
LARGE_INTEGER li;
-
-
li.QuadPart =
0;
-
-
-
if (!SetWaitableTimer(hTimer, &li, pThis->_nInterval, pThis->_callbackFunc, pThis, FALSE))
-
-
{
-
-
CloseHandle(hTimer);
-
-
return
0;
-
-
}
-
-
-
do
-
{
-
SleepEx(pThis->_nInterval, TRUE);
-
-
}
while (pThis->_bRunning);
-
CloseHandle(hTimer);
-
return
0;
-
}