@转载:链接
#include <iostream>
#include <chrono>
using namespace std;
typedef void (*BACKCALLFUNC)(void*);
void setTimer(unsigned int id, int msec, BACKCALLFUNC backCallFunc)
{
if (msec < 0)
{
return;
}
auto start = std::chrono::system_clock::now(); //获取当前系统时间
double totalTime = 0;
while (1)
{
auto finish = std::chrono::system_clock::now();
totalTime = (double)std::chrono::duration_cast<std::chrono::milliseconds>(finish - start).count(); //将时间转换成ms
if (totalTime > msec)
{
backCallFunc(&totalTime);
break;
}
}
}
//回调函数
void backCallFunc(void* arg)
{
cout << *(double*)arg << "ms" << endl;
}
int main()
{
while (1)
{
setTimer(1, 2000, backCallFunc); //1为id,2000为msec(毫秒量),backCallFunc为回调函数
}
return 0;
}