boost::asio::steady_timer基础使用

本文详细介绍了C++中定时器的演变过程,从早期的boost::asio::deadline_timer到更符合C++标准的boost::asio::steady_timer。通过实例代码展示了如何使用steady_timer进行异步等待和时间控制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

看到书上说,boost::asio::deadline_timer是asio早期版本提供的定时器,使用boost.date_time库提供时间支持。貌似deadline_timer会被逐渐淘汰。所以学了一下更符合C++标准的steady_timer,

//boost::posix_time::to_simple_string函数需要这两个头文件
#include <boost/date_time.hpp>
#include <boost/date_time/posix_time/ptime.hpp>
//使用boost.chrono代替std.chrono,
#define BOOST_ASIO_DISABLE_STD_CHRONO
#include <boost/asio.hpp>
#include <boost/asio/steady_timer.hpp>
#include <boost/asio/placeholders.hpp>
#include <boost/thread.hpp>

class MyClass
{
public:
    MyClass() :m_work(m_io), m_timer(m_io){}
public:
    boost::thread_group m_thgp;
    boost::asio::io_service m_io;
    boost::asio::io_service::work m_work;
    boost::asio::steady_timer m_timer;
public:
    void Init()
    {
        boost::system::error_code errCode;
        m_thgp.create_thread(boost::bind(&boost::asio::io_service::run, boost::ref(m_io), errCode));
        std::cout << "Init_1, " << LocalTime() << std::endl;
        m_timer.expires_from_now(boost::chrono::milliseconds(4000)); //设置过期时间长度
#if 0
        m_timer.expires_from_now(std::chrono::milliseconds(4000));
#endif
        std::cout << "Init_2, " << LocalTime() << std::endl;
        m_timer.async_wait(boost::bind(&MyClass::Test, this, boost::asio::placeholders::error));//异步等待
        std::cout << "Init_3, " << LocalTime() << std::endl;
        //由Console可知, 函数立即返回了, 定时器的expires_from_now是由完成端口处理的
    }
    void Stop()
    {
        std::cout << "Stop_1, " << LocalTime() << std::endl;
        m_timer.cancel();  // 取消所有handler
        m_work.~work();
        m_thgp.join_all();
        std::cout << "Stop_2, " << LocalTime() << std::endl;
    }
    static std::string LocalTime()
    {
        return boost::posix_time::to_simple_string(boost::posix_time::microsec_clock::local_time());
    }

    void Test(const boost::system::error_code& ec)
    {
        printf("test_1, %s, ec.value=%d, ec.message=%s\n", LocalTime().c_str(), ec.value(), ec.message().c_str());
        if (ec)  return;
        m_timer.expires_from_now(boost::chrono::milliseconds(4000));
#if 0
        m_timer.expires_from_now(std::chrono::milliseconds(4000));
#endif
        std::cout << "test_2, " << LocalTime() << std::endl;
        m_timer.async_wait(boost::bind(&MyClass::Test, boost::ref(*this), _1));
#if 0
        m_timer.async_wait(boost::bind(&MyClass::Test, this, _1));
        m_timer.async_wait(boost::bind(&MyClass::Test, this, boost::asio::placeholders::error));
#endif
        std::cout << "test_3, " << LocalTime() << std::endl;
    }
};

int main(int argc, char** argv)
{
    MyClass my;
    my.Init();
    for (int i = 0; i < 30; ++i)
    {
        boost::this_thread::sleep_for(boost::chrono::milliseconds(1000));
    }
    my.Stop();
    std::cout << "press ENTER to exit..." << std::endl;
    std::cin.sync();
    while (getchar() != '\n') {}
}

完。

`boost::asio::steady_timer ctrlTxTimer;` 是 Boost.Asio 库中的一个异步定时器对象。Boost.Asio 是一个用于网络和底层 I/O 编程的跨平台 C++ 库,广泛用于开发高性能网络应用程序。 具体来说,`ctrlTxTimer` 是一个 `steady_timer` 对象,它可以用于在异步操作中设置定时器。以下是一些关于 `boost::asio::steady_timer` 的关键点: 1. **构造函数**:`steady_timer` 可以接受一个 `io_context` 对象作为参数,`io_context` 是 Boost.Asio 的核心类,用于处理异步操作。 ```cpp boost::asio::io_context io; boost::asio::steady_timer ctrlTxTimer(io); ``` 2. **定时器操作**:`async_wait` 方法用于设置一个异步等待操作,当定时器到期时,会调用指定的回调函数。 ```cpp ctrlTxTimer.async_wait([](const boost::system::error_code& error){ if (!error) { // 定时器到期的处理逻辑 } }); ``` 3. **取消定时器**:可以使用 `cancel` 方法取消定时器。 ```cpp ctrlTxTimer.cancel(); ``` 4. **示例代码**:以下是一个简单的示例,展示了如何使用 `steady_timer` 设置一个定时器,并在定时器到期时执行回调函数。 ```cpp #include <boost/asio.hpp> #include <iostream> void timerHandler(const boost::system::error_code& error) { if (!error) { std::cout << "Timer expired!" << std::endl; } } int main() { boost::asio::io_context io; boost::asio::steady_timer ctrlTxTimer(io); ctrlTxTimer.expires_after(std::chrono::seconds(2)); ctrlTxTimer.async_wait(timerHandler); io.run(); return 0; } ``` 在这个示例中,定时器被设置为在 2 秒后到期,到期后会调用 `timerHandler` 函数,输出 "Timer expired!"。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值