可以使用chrono库实现简单的周期周期性定时任务
#include "stdafx.h"
#include <iostream>
#include <chrono>
#include <thread>
using namespace std;
using namespace std::chrono;
class CSimpleTimer
{
public:
CSimpleTimer() :m_begin(high_resolution_clock::now()){}
void reset() { m_begin = high_resolution_clock::now(); }
template<typename Duration = microseconds>
int64_t elapsed() const
{
return duration_cast<Duration>(high_resolution_clock::now() - m_begin).count();
}
//micro_s
int64_t elapsed_micro() const
{
return elapsed<microseconds>();
}
//mill_s
int64_t eapsed_ms() const
{
return elapsed<milliseconds>();
}
// ns
int64_t elapsed_nano()const
{
return elapsed<nanoseconds>();
}
// s
int64_t elapsed_seconds()const
{
return elapsed<seconds>();
}
private:
time_point<high_resolution_clock> m_begin;
};
void doJob()
{
std::cout << "shining days" << std::endl;
}
int main()
{
CSimpleTimer t;
while (true)
{
//1s task
if (t.elapsed_micro() >= 1000000)
{
t.reset();
doJob();
}
std::this_thread::yield();
}
}
上面的代码每秒打印一个字符串