Skip to content

Timers

Timers

Timers are useful to applications that need to perform some operations once every x time units, including timeouts for servers

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
find_package(Asio 1.21.0 QUIET)
if (NOT Asio_FOUND)
    FetchContent_Declare(asio GIT_REPOSITORY https://github.com/chriskohlhoff/asio.git GIT_TAG asio-1-21-0)
    FetchContent_GetProperties(asio)
    if (NOT asio_POPULATED)
        FetchContent_Populate(asio)
        add_library(asio INTERFACE)
        target_include_directories(asio INTERFACE ${asio_SOURCE_DIR}/asio/include)
        target_compile_definitions(asio INTERFACE ASIO_STANDALONE ASIO_NO_DEPRECATED)
        target_link_libraries(asio INTERFACE Threads::Threads)
    endif ()
endif()

1
2
add_executable(timers timers.cpp)
target_link_libraries(timers asio)

1
asio::io_context io_context;

1
2
3
asio::steady_timer t(io_context, std::chrono::seconds(3));
t.wait();
std::cout << "Sync Timer expired" << '\n';

1
asio::steady_timer t1(io_context, std::chrono::seconds(3));

1
2
3
4
5
6
7
t1.async_wait([](std::error_code ec) {
    if (!ec) {
        std::cout << "Timer 1 expired" << '\n';
    } else {
        std::cout << "Timer 1 error" << '\n';
    }
});

1
asio::system_timer t2(io_context, std::chrono::seconds(3));

1
2
3
4
5
6
7
t2.async_wait([](std::error_code ec) {
    if (!ec) {
        std::cout << "Timer 2 expired" << '\n';
    } else {
        std::cout << "Timer 2 error" << '\n';
    }
});

1
asio::high_resolution_timer t3(io_context, std::chrono::seconds(3));

1
2
3
4
5
6
7
t3.async_wait([](std::error_code ec) {
    if (!ec) {
        std::cout << "Timer 3 expired" << '\n';
    } else {
        std::cout << "Timer 3 error" << '\n';
    }
});

1
2
3
4
asio::thread_pool pool;
for (size_t i = 0; i < std::thread::hardware_concurrency(); ++i) {
    asio::post(pool, [&io_context] { io_context.run(); });
}

Share Snippets