一.同步定时器,如下:
#include <iostream>
#include <boost/asio.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
int main(int argc,char** argv){
boost::asio::io_service ios;
boost::asio::deadline_timert(ios,boost::posix_time::seconds(2));
std::cout<<t.expires_at()<<std::endl;
t.wait();
std::cout<<"helloworld"<<std::endl;
return 0;
}
二.异步定时器,如下:
#include <iostream>
#include <boost/asio.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
void print(const boost::system::error_code& e){
std::cout<<"hello asio"<<std::endl;
}
int main(int argc,char** argv){
boost::asio::io_service ios;
boost::asio::deadline_timer t(ios,boost::posix_time::seconds(2));
t.async_wait(print);
std::cout<<"it show before texpired."<<std::endl;
ios.run();
return 0;
}
#include <iostream>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
using namespace boost;
using namespace boost::asio;
void print1(){
std::cout<<"hello asio"<<std::endl;
}
void print2(){
std::cout<<"hello boost"<<std::endl;
}
三.用bind实现异步定时器,如下:
#include <iostream>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/function.hpp>
#include<boost/date_time/posix_time/posix_time.hpp>
using namespace boost;
using namespace boost::asio;
class a_timer{
private:
int count;
int count_max;
function<void()> f;
deadline_timer t;
public:
template<typename F>
a_timer(io_service& ios,int x,Ffunc):f(func),count_max(x),count(0)
,t(ios,posix_time::millisec(500))
{
t.async_wait(bind(&a_timer::call_func,this,placeholders::error));
}
void call_func(const system::error_code& e){
if(count >= count_max){
return;
}
++count;
f();
t.expires_at(t.expires_at() +posix_time::millisec(500));
t.async_wait(bind(&a_timer::call_func,this,placeholders::error));
}
};
int main(int argc,char** argv){
io_service ios;
a_timer at1(ios,5,print1);
a_timer at2(ios,5,print2);
ios.run();
return 0;
}