自己写的C++定时器

#头文件CTime.h

#ifndef CTIMER_H
#define CTIMER_H

#include <windows.h>

typedef void (*TimerProcFunc)(void* userPtr);

class CTimer
{
public:
 CTimer();
 virtual ~CTimer();

 int settimer(unsigned int uElaps, TimerProcFunc func, void *user);

 void killtimer();

protected:
 static unsigned __stdcall TimeThread(void * pParam);

private:
 unsigned int m_uElaps;
 void* m_pUser;
 TimerProcFunc m_callBackFunc;
 HANDLE m_hThread;
};


#endif

 

#源文件CTime.cpp

#include "stdafx.h"
#include "CTimer.h"
#include <time.h>
#include <process.h>

CTimer::CTimer()
 : m_pUser(NULL)
 , m_callBackFunc(NULL)
 , m_hThread(NULL)
 , m_uElaps(1)
{

}

CTimer::~CTimer()
{
 if(m_hThread)
 {
  CloseHandle(m_hThread);
  m_hThread = NULL;
 }
}

unsigned __stdcall CTimer::TimeThread(void * pParam)
{
 CTimer *pTimer = (CTimer*)pParam;
 time_t t1, t2; 
 double  Diff = 0;


 /*获取系统当前时间*/
 t1 = time(NULL); 

 while(1)
 {
  /*以秒为单位获取系统当前时间*/
  t2 = time(NULL); 

  Diff = difftime(t2,t1);

  if((int)Diff == pTimer->m_uElaps)
  {

   t1 = t2; 
   if (pTimer->m_callBackFunc)
   {
    pTimer->m_callBackFunc(pTimer->m_pUser);
   }
  }     
 } 
 return 0;

}

int CTimer::settimer(unsigned int uElaps, TimerProcFunc func, void *user)
{
 if (m_hThread)
 {
  return -1;
 }

 m_uElaps = uElaps;
 m_callBackFunc = func;

 unsigned threadID;
 m_hThread = (HANDLE)_beginthreadex(NULL, 0, CTimer::TimeThread, this, 0, &threadID);
 if (m_hThread == 0)
 {
  return -1;
 }
 else
 {
  return 0;
 }
}

void CTimer::killtimer()
{
 if(m_hThread)
 {
  CloseHandle(m_hThread);
  m_hThread = NULL;
 }
}

 #测试例子

#include "stdafx.h"
#include "CTimer.h"

void ProcFunc(void* userPtr)
{
 printf("\nTime is here\n");
}

int _tmain(int argc, _TCHAR* argv[])
{
 CTimer myTimer;

 myTimer.settimer(2, ProcFunc, NULL);

 getchar();

 return 0;
} 


 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值