Last active
July 4, 2024 19:47
-
-
Save Angeart/dc8d6902b7d59923caf4a11f78d52ffa to your computer and use it in GitHub Desktop.
boost repeating_timer
This file contains hidden or 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
| #include <iostream> | |
| #include <cstdlib> | |
| #include <boost/asio.hpp> | |
| #include <boost/bind.hpp> | |
| #include <boost/date_time/posix_time/posix_time.hpp> | |
| #include <functional> | |
| #include <thread> | |
| #include <chrono> | |
| void hoge(const boost::system::error_code& /*e*/) { | |
| std::cout << "ok" << std::endl; | |
| }; | |
| class repeating_timer { | |
| public: | |
| repeating_timer(boost::asio::io_service& io_, boost::posix_time::time_duration interval_) | |
| : timer(io_, interval_) | |
| , interval(interval_) | |
| {} | |
| void start(std::function<void(const boost::system::error_code&)> cb_) { | |
| this->cb = cb_; | |
| init(); | |
| } | |
| void wrap(const boost::system::error_code& e) { | |
| this->cb(e); | |
| this->timer.expires_at(this->timer.expires_at() + interval); | |
| init(); | |
| } | |
| void init() { | |
| this->timer.async_wait(boost::bind(&repeating_timer::wrap, this, boost::asio::placeholders::error)); | |
| } | |
| private: | |
| boost::asio::deadline_timer timer; | |
| std::function<void(const boost::system::error_code&)> cb; | |
| boost::posix_time::time_duration interval; | |
| }; | |
| int main() | |
| { | |
| boost::asio::io_service io; | |
| std::thread t([&](){ | |
| auto interval = boost::posix_time::seconds(1); | |
| repeating_timer timer(io, interval); | |
| timer.start(hoge); | |
| io.run(); | |
| }); | |
| std::this_thread::sleep_for(std::chrono::seconds(5)); | |
| io.stop(); | |
| t.join(); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment