廢話不多說, asio的原理請百度其它博文, 百度上好多deadline_timer的例子都是單次定時, 或者是封裝的很長. 本文寫的是一個超簡單的例子來實現循環定時, 注意這個循環的週期是可變的, 可以每5秒固定週期執行, 也可以1秒/5秒/2秒變週期執行, 或者指定一個絕對時間來執行.
#include "stdafx.h"
#include <boost/asio.hpp>
using namespace std;
using namespace boost;
using namespace boost::posix_time;
using namespace boost::asio;
io_service io;
deadline_timer ti5s(io, seconds(5));
void timer_wait5s(const boost::system::error_code& err)
{
cout << "time out: 5s" << endl;
ti5s.expires_from_now(seconds(5)); // 用法1.
//ti5s.expires_at(ti5s.expires_at() + seconds(5)); // 用法2.
ti5s.async_wait(timer_wait5s);
}
int _tmain(int argc, _TCHAR* argv[])
{
ti5s.async_wait(timer_wait5s);
io.run();
return 0;
}
有一點要說明的:
- 代碼中標的用法1: expires_from_now函數, 用於在當前時間之後的5秒再次執行異步, 這是個相對時間
- 代碼中標的用法2: expires_at函數, 用於指定時間後再次執行異步, 這是個絕對時間, 在代碼裏的絕對時間是ti5s.expires_at(ti5s.expires_at() + seconds(5)); 也就是從現在開始後5秒這個絕對時間點