I want to create periodic task that perform 1 time per second. But in my case boost::asio::deadline_timer should not be global variable.
boost::asio::io_service _io;
void handler(const boost::system::error_code, int a) {
boost::asio::deadline_timer timer(_io);
//do task
timer.expires_from_now(boost::posix_time::seconds(1));
timer.async_wait(std::bind(handler, _1, a));
}
boost::asio::deadline_timer timer(_io);
timer.expires_from_now(boost::posix_time::seconds(1));
timer.async_wait(std::bind(handler, _1, 1));
Update I get it. You want dynamically allocated timers?
#include <boost/asio.hpp>
#include <boost/make_shared.hpp>
using namespace boost;
using Timer = shared_ptr<asio::deadline_timer>;
asio::io_service _io;
void handler(int a, const system::error_code& = {}, Timer timer = make_shared<Timer::element_type>(_io)) {
std::cout << "hello world\n";
timer->expires_from_now(posix_time::seconds(1));
timer->async_wait(bind(handler, a, asio::placeholders::error, timer));
}
int main() {
handler(42);
_io.run();
}
The trick is boost::bind
binds to boost::shared_ptr
and keep a copy of it - extending the lifetime of the timer object
A deadline timer, firing every second, and not using any globals:
#include <boost/asio.hpp>
#include <boost/thread.hpp>
using namespace boost;
int main() {
thread t([] {
asio::io_service io;
asio::deadline_timer dt(io, posix_time::seconds(1));
function<void(system::error_code)> ll = [&](system::error_code ec) {
if (!ec) {
puts("hello world");
dt.expires_from_now(posix_time::seconds(1));
dt.async_wait(ll);
}
};
ll({});
io.run();
});
this_thread::sleep_for(chrono::seconds(2));
std::cout << "async\n";
t.join();
}
Output:
Hello world
Hello world
async
Hello world
Hello world
....
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다