#include#include #include int main() { std::chrono::milliseconds interval(1000); std::chrono::steady_clock::time_point nextTime = std::chrono::steady_clock::now() + interval; while (true) { std::this_thread::sleep_until(nextTime); // wait until the next interval std::cout << "Timer expired!\n"; nextTime += interval; // restart the timer } return 0; }
#includeThis code uses the Boost library's `asio` module to create a timer object that calls a callback function when it expires. The callback function prints a message and restarts the timer by setting a new expiration time. The `io.run()` function runs the I/O service and allows the timer to continue running. Both of these code examples use different libraries/packages: the first example uses only the standard library, while the second example uses the Boost library.#include int main() { boost::asio::io_service io; boost::asio::deadline_timer timer(io, boost::posix_time::seconds(1)); timer.async_wait([&](const boost::system::error_code& error) { if (error != boost::asio::error::operation_aborted) { std::cout << "Timer expired!\n"; timer.expires_at(timer.expires_at() + boost::posix_time::seconds(1)); // restart the timer timer.async_wait([&](const boost::system::error_code& error) { std::cout << "Timer expired again!\n"; }); } }); io.run(); return 0; }