- #include <iostream>
- #include <boost/asio.hpp>
- int main()
- {
- boost::asio::io_service io;
- boost::asio::deadline_timer timer(io, boost::posix_time::seconds(3));
- timer.wait();
- std::cout << "Hello, world! ";
- return 0;
- }
再来个异步的:
- void print(const boost::system::error_code& /*e*/)
- {
- std::cout << "Hello, world! ";
- }
- int main()
- {
- boost::asio::io_service io;
- boost::asio::deadline_timer timer(io, boost::posix_time::seconds(5));
- timer.async_wait(&print);
- io.run();
- return 0;
- }
上次演示了基本用法,但它只能发生一次.
问题是怎么定义一个重复发生的定时器(就是隔一定的时间它就会发生一次.)呢,下面的代码就是了, 关键在于回调函数中更改了延时不断的延长定时器
- void print(const boost::system::error_code& e,
- boost::asio::deadline_timer* t)
- {
- cout<<"ddd"<<endl;
- t->expires_at(t->expires_at()+ boost::posix_time::seconds(1));
- t->async_wait(boost::bind(print,boost::asio::placeholders::error,t));
- }
- void test1()
- {
- boost::asio::io_service io;
- boost::asio::deadline_timer t(io, boost::posix_time::seconds(1));
- t.async_wait(boost::bind(print,boost::asio::placeholders::error,&t));
- io.run();
- }
- int _tmain(int argc, _TCHAR* argv[])
- {
- test1();
- system("pause");
- return 0;
- }