在工作中遇到一个问题,本来准备弄个定时器,隔一段时间就去跑一个函数,刷新数据的,最后还是把任务交给了前端,但是在网上查询了资料,可以想下面这么写,就可以一直跑了,先做个总结,以后还是会用到的。
#include<boost/asio.hpp>
#include<boost/date_time/posix_time/posix_time.hpp>
#include<boost/bind/bind.hpp>
int iCount = 0;
void sync_wait_handle(const boost::system::error_code &error_code,boost::asio::deadline_timer* timer)
{
std::cout<<"iCount :"<<iCount++<<std::endl;
timer->expires_at(timer->expires_at() + boost::posix_time::seconds(1));
timer->async_wait(boost::bind(sync_wait_handle,boost::asio::placeholders::error,timer));
}
void testWait()
{
boost::asio::io_service io_service;
boost::asio::deadline_timer timer(io_service,boost::posix_time::seconds(1));
timer.async_wait(boost::bind(sync_wait_handle,boost::asio::placeholders::error(),&timer));
io_service.run();
}
int main(int argc, char* argv[])
{
testWait();
return 0;
}
运行效果图: