自己写一个简单的定时器settimer

时间:2022-11-02 19:37:14


MyTimer.h

#pragma once
#include <process.h>

typedef void (*TimerProCB)(int Handler, void* context);

typedef struct TIMER_PARAM
{
int Handler;
void* context;
TimerProCB timepro;
unsigned int elapse;
}TIMER_PARAM;

class CMyTimer
{
public:
CMyTimer(void);
~CMyTimer(void);

bool Settimer(TIMER_PARAM param);

static unsigned int __stdcall WaitPro(void * pParam);
};

MyTimer.cpp

#include "StdAfx.h"
#include "MyTimer.h"



CMyTimer::CMyTimer(void)
{
}


CMyTimer::~CMyTimer(void)
{
}

bool CMyTimer::Settimer(TIMER_PARAM param)
{
TIMER_PARAM* timeparam= new TIMER_PARAM;
memcpy(timeparam, ¶m, sizeof(TIMER_PARAM));
HANDLE hThread = (HANDLE)_beginthreadex(0, 0, WaitPro, (void*)timeparam, 0, 0);
CloseHandle(hThread);
return true;
}

unsigned int __stdcall CMyTimer::WaitPro(void * pParam)
{
TIMER_PARAM* timeparam = (TIMER_PARAM*)pParam;
Sleep(timeparam->elapse);
timeparam->timepro(timeparam->Handler, timeparam->context);
delete timeparam;
return 0;
}


使用

TIMER_PARAM param;
param.context = this;
param.elapse = WAIT_PORT_ELAPSE;
param.Handler = port;
param.timepro = TimeProc;
myTimer.Settimer(param);

TimeProc为回调函数, WAIT_PORT_ELAPSE为等待时间, TIMER_PARAM可以自己定义,自己发挥