使用boost :: asio创建计时器

时间:2015-01-19 20:16:11

标签: c++ boost boost-asio

我想创建每秒执行1次的定期任务。但就我而言,boost :: asio :: deadline_timer不应该是全局变量。

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));

1 个答案:

答案 0 :(得分:3)

更新我明白了。您想要动态分配的计时器吗?

<强> Live On Coliru

#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();
}

技巧是boost::bind绑定到boost::shared_ptr并保留它的副本 - 延长计时器对象的生命周期


截止时间计时器,每秒触发一次,而不使用任何全局变量:

#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();
}

输出:

Hello world
Hello world
async
Hello world
Hello world
....