回调函数讲解参考这篇
#ifndef _TASKTIMER_H
#define _TASKTIMER_H
#include <iostream>
#ifdef WIN32
#include <windows.h>
#else
#include <unistd.h>
#include <sys/time.h>
#include <netinet/in.h>
#include <pthread.h>
#endif
//定义回调函数
typedef void (*timerCallBack)(void* param);
class TaskTimer
{
public:
TaskTimer(int timeSecond);
~TaskTimer(void);
public:
void start();
void stop();
void setTimerFun(timerCallBack fun, void* param);
static void * timer(void* context);
public:
timerCallBack m_timerFun;
void* m_pFunParam;
public:
int m_timeSecond;
bool m_bTimerStop;
static unsigned long getTickCount(void);
};
#endif
#include <stdio.h>
#include "TaskTimer.h"
#include <glog/logging.h>
#include "BCFThread.hpp"
using namespace BCF;
TaskTimer::TaskTimer(int timeSecond)
{
m_timeSecond = timeSecond;
m_bTimerStop = false;
m_timerFun = NULL;
m_pFunParam = NULL;
}
TaskTimer::~TaskTimer(void)
{
LOG(INFO) << "exec ~ taskTime()";
stop();
}
void TaskTimer::start()
{
BCF::ThreadHandle pid;
int ret = BCF::BCFThread::createThread(TaskTimer::timer, (void*)this, NULL, pid);
if(ret != 0) {
LOG(ERROR) << "create pthread failed!";
}
}
void TaskTimer::stop()
{
m_bTimerStop = true;
}
void TaskTimer::setTimerFun(timerCallBack fun, void* param)
{
m_timerFun = fun;
m_pFunParam = param;
}
void * TaskTimer::timer(void* context)
{
TaskTimer* pthis = (TaskTimer*)context;
if (pthis == NULL) {
return NULL;
}
unsigned int curTm = 0;
unsigned int lastTm = 0;
while (!pthis->m_bTimerStop) {
curTm = getTickCount();
//LOG(INFO)<<"curTm:"<<curTm<<" lastTm:"<<lastTm<< " compare time:"<<pthis->m_timeSecond*1000;
if ((curTm - lastTm) >= ((pthis->m_timeSecond) * 1000)) {
lastTm = curTm;
} else {
usleep(1000 * 1000);
continue;
}
//执行定时器函数
if (pthis->m_timerFun != NULL) {
pthis->m_timerFun(pthis->m_pFunParam);
}
}
LOG(INFO) << "exit";
return NULL;
}
unsigned long TaskTimer::getTickCount(void)
{
unsigned long curTime;
struct timeval current;
gettimeofday(¤t, NULL);
curTime = current.tv_sec * 1000 + current.tv_usec / 1000;
return curTime;
}