该定时器类继承一个Thread类,在线程函数里,每隔一定的时间,执行一次TimerHandler.
Thread.h
- #ifndef _THREAD_H_
- #define _THREAD_H_
- #include <Windows.h>
- class Thread
- {
- public:
- Thread();
- virtual ~Thread();
- virtual void Run() = 0;
- void Start();
- void Stop();
- bool IsStop();
- protected:
- static DWORD WINAPI ThreadProc(LPVOID p);
- private:
- bool m_stopFlag;
- HANDLE m_hThread;
- };
- #endif
Thread.cpp
- #include "Thread.h"
- Thread::Thread()
- :m_stopFlag(false)
- ,m_hThread(INVALID_HANDLE_VALUE)
- {
- }
- Thread::~Thread()
- {
- Stop();
- }
- void Thread::Start()
- {
- unsigned long *p =NULL;
- m_hThread = ::CreateThread(NULL, 0, ThreadProc, this, 0, p);
- }
- DWORD WINAPI Thread::ThreadProc(LPVOID p)
- {
- Thread* thread = (Thread*)p;
- thread->Run();
- CloseHandle( thread->m_hThread );
- thread->m_hThread= INVALID_HANDLE_VALUE;
- return 0;
- }
- void Thread::Stop()
- {
- m_stopFlag = true;
- if(m_hThread != INVALID_HANDLE_VALUE)
- {
- if(WaitForSingleObject(m_hThread,INFINITE) != WAIT_ABANDONED)
- {
- CloseHandle(m_hThread);
- }
- m_hThread = INVALID_HANDLE_VALUE;
- }
- }
- bool Thread::IsStop()
- {
- return m_stopFlag;
- }
Timer.h
- #ifndef _TIMER_H_
- #define _TIMER_H_
- #include <Windows.h>
- #include "Thread.h"
- class Timer : public Thread
- {
- typedef void(CALLBACK *Timerfunc)(void* p);
- typedef Timerfunc TimerHandler;
- public:
- Timer()
- :m_handler(0)
- ,m_interval(-1)
- {
- }
- void registerHandler(TimerHandler handler, void* p)
- {
- m_handler = handler;
- m_parameter = p;
- }
- void setInterval(int millisecond)
- {
- m_interval = millisecond;
- }
- void Run()
- {
- unsigned long tickNow = ::GetTickCount();
- unsigned long tickLastTime = tickNow;
- while(!IsStop())
- {
- tickNow = ::GetTickCount();
- if(tickNow - tickLastTime > m_interval)
- {
- if(m_handler)
- {
- (*m_handler)(m_parameter);
- }
- tickLastTime = ::GetTickCount();
- }
- ::Sleep(1);
- }
- }
- void Cancel()
- {
- Stop();
- }
- private:
- TimerHandler m_handler;
- int m_interval;
- void* m_parameter;
- };
- #endif
test.cpp
- #include <iostream>
- #include <Windows.h>
- #include "Timer.h"
- using namespace std;
- void CALLBACK TimerProc(void* p)
- {
- int i = *((int*)p);
- cout << i << endl;
- }
- void main()
- {
- Timer timer;
- int i = 10;
- int *p = &i;
- timer.registerHandler(TimerProc, p);
- timer.setInterval(1000);
- timer.Start();
- ::Sleep(1000);
- for(; i > 0; i--)
- {
- cout << "hello" << endl;
- ::Sleep(1000);
- }
- timer.Cancel();
- system("pause");
- }
运行结果
hello
10
hello
9
hello
8
hello
7
hello
6
hello
5
hello
4
hello
3
hello
2
hello
1
阅读(29853) | 评论(0) | 转发(0) |