同步定时器
#include <cstdio>
#include <iostream>
#include <boost/asio.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
int main()
{
boost::asio::io_service io;
boost::asio::deadline_timer t(io, boost::posix_time::seconds(5));
t.wait();//同步定时器,5后被调用
std::cout << "Hello, world!
";
return 0;
}
链接库 -lpthread -lboost_system
异步定时器
#include <cstdio>
#include <iostream>
#include <boost/asio.hpp>
#include <boost/thread.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
using namespace std;
/****************************************************************
函 数:Print
参 数:void
返回值:const boost::system::error_code &ec -- 执行失败原因
说 明:回调函数
****************************************************************/
void Print(const boost::system::error_code &ec)
{
cout << "Hello World!" << endl;
cout << boost::this_thread::get_id() << endl;//id一致, 在同一个线程中执行
}
int main()
{
cout << boost::this_thread::get_id() << endl;//id一致, 在同一个线程中执行
boost::asio::io_service io;
boost::asio::deadline_timer t(io, boost::posix_time::seconds(5));
t.async_wait(Print);//异步定时器,立马返回
cout << "to run" << endl;
io.run(); //异步IO调度
cout << "exit" << endl;
return EXIT_SUCCESS;
}
回调函数绑定参数 boost::bind()
/****************************************************************
函 数:Print
参 数:const boost::system::error_code &ec -- 执行失败原因
参 数:boost::asio::deadline_timer* pt -- 定时器
参 数:int * pcount -- 执行次数
返回值:void
说 明:回调函数
****************************************************************/
void Print(const boost::system::error_code &ec, boost::asio::deadline_timer* pt, int* pcount)
{
if (*pcount < 3)
{
cout << "count = " << *pcount << endl;
(*pcount)++;
//推迟定时器的终止时间,确保回调函数不会在所需时间内到期
pt->expires_at(pt->expires_at() + boost::posix_time::seconds(5));
//重新绑定任务
pt->async_wait(boost::bind(Print, boost::asio::placeholders::error, pt, pcount));
}
}
int main()
{
boost::asio::io_service io;
boost::asio::deadline_timer t(io, boost::posix_time::seconds(5));
int count = 0;
t.async_wait(boost::bind(Print, boost::asio::placeholders::error, &t, &count));
cout << "to run" << endl;
io.run();
cout << "Final count is " << count << "
";//3
cout << "exit" << endl;
return 0;
}