Last active
May 5, 2022 16:44
-
-
Save micfan/680f28bda9f2544423d116e470dd6f39 to your computer and use it in GitHub Desktop.
boost-asio-ticker-example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// environment: C++14, gcc-11.2 | |
// build command: g++ -o ./boost_asio_ticker boost_asio_ticker.cpp -lpthread | |
#include <iostream> | |
#include <boost/asio.hpp> | |
#include <boost/bind/bind.hpp> | |
#include <chrono> | |
class Ticker { | |
public: | |
Ticker(boost::asio::io_context &io, const std::chrono::seconds& interval, std::function<void()> handler) | |
: timer_(io, interval) | |
, interval_(interval) | |
, handler_(std::move(handler)) { | |
} | |
void async_start() { | |
timer_.async_wait([&](const boost::system::error_code ec) { | |
on_tick(ec); | |
}); | |
} | |
void on_tick(const boost::system::error_code ec) { | |
handler_(); | |
timer_.expires_from_now(interval_); | |
timer_.async_wait(boost::bind(&Ticker::on_tick, this, boost::asio::placeholders::error)); | |
} | |
size_t stop() { | |
return timer_.cancel(); | |
} | |
private: | |
boost::asio::steady_timer timer_; | |
std::chrono::seconds interval_; | |
std::function<void()> handler_; | |
}; | |
void print() { | |
std::cout << "Hello, World!" << std::endl; | |
} | |
int main() | |
{ | |
boost::asio::io_context io; | |
using namespace std::chrono_literals; | |
auto interval = 3s; // (since C++14) | |
Ticker t(io, interval, print); | |
t.async_start(); | |
io.run(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment