C++ 使用Boost库的定时器

flyfish

运行环境arm

#include <iostream>
#include <boost/asio.hpp>
#include <boost/bind/bind.hpp>

class TestTimerExample
{
public:
    TestTimerExample(boost::asio::io_context& io)
        : timer_(io, boost::asio::chrono::seconds(10)),
        count_(0)
    {
        timer_.async_wait(boost::bind(&TestTimerExample::print, this));
    }

    ~TestTimerExample()
    {
        std::cout << "Final count is " << count_ << std::endl;
    }

    void print()
    {
        if (count_ < 5)
        {
            std::cout << count_ << std::endl;
            ++count_;

            timer_.expires_at(timer_.expiry() + boost::asio::chrono::seconds(5));
            timer_.async_wait(boost::bind(&TestTimerExample::print, this));
        }
    }

private:
    boost::asio::steady_timer timer_;
    int count_;
};

int main()
{
    boost::asio::io_context io;
    TestTimerExample p(io);
    io.run();

    return 0;
}

10秒钟之后启动定时器,时间间隔是5秒
CMakeLists.txt
需要改变下BOOST_PREFIX自己boost库所在目录

cmake_minimum_required(VERSION 3.5)

project(BoostTimerTest LANGUAGES CXX)

set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED ON)


set(BOOST_PREFIX /media/a/build/out/arm64-v8a/)

set(BOOST_INCLUDE_DIR "${BOOST_PREFIX}/include/boost-1_82/")
set(BOOST_LIB_DIR "${BOOST_PREFIX}/lib/")



set(BOOST_LIBS
        "${BOOST_LIB_DIR}/libboost_filesystem-clang-mt-a64-1_82.a"
        "${BOOST_LIB_DIR}libboost_thread-clang-mt-a64-1_82.a"

    )


include_directories(
    ${BOOST_INCLUDE_DIR}

)


add_executable(BoostTimerTest main.cpp)
target_link_libraries(BoostTimerTest  "${BOOST_LIBS}"   -lm  -ldl -frtti -fexceptions)
install(TARGETS BoostTimerTest
    LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
    RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
)

C++ 使用Poco库的定时器
Qt for Android 定时器

08-10 18:15