From ba04ffb5a94fd47d8acc57c7a6be4d31624d2c23 Mon Sep 17 00:00:00 2001 From: "William A. Kennington III" Date: Thu, 20 Sep 2018 11:35:11 -0700 Subject: utility/timer: Implement oneshot timers This change is meant to enable users of the old openbmc timer class to trivially use the timer if they only want single executions. It also makes setting up the timer less verbose if you do not already know the timeout interval. Tested: Run through unit tests and did a sample integration with phosphor-watchdog and phosphor-networkd. Verified that the new oneshot example works as expected. Change-Id: I2cd006d1f19fff99bce3f732a16eac9ca9553666 Signed-off-by: William A. Kennington III --- example/delayed_echo.cpp | 59 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 example/delayed_echo.cpp (limited to 'example/delayed_echo.cpp') diff --git a/example/delayed_echo.cpp b/example/delayed_echo.cpp new file mode 100644 index 0000000..e7fc33b --- /dev/null +++ b/example/delayed_echo.cpp @@ -0,0 +1,59 @@ +/** + * Reads stdin looking for a string, and coalesces that buffer until stdin + * is calm for the passed in number of seconds. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using sdeventplus::Clock; +using sdeventplus::ClockId; +using sdeventplus::Event; +using sdeventplus::source::IO; + +constexpr auto clockId = ClockId::RealTime; +using Timer = sdeventplus::utility::Timer; + +int main(int argc, char* argv[]) +{ + if (argc != 2) + { + fprintf(stderr, "Usage: %s [seconds]\n", argv[0]); + return 1; + } + + std::chrono::seconds delay(std::stoul(argv[1])); + + auto event = Event::get_default(); + + std::string content; + auto timerCb = [&](Timer&) { + printf("%s", content.c_str()); + content.clear(); + }; + Timer timer(event, std::move(timerCb)); + + auto ioCb = [&](IO&, int fd, uint32_t) { + std::array buffer; + ssize_t bytes = read(fd, buffer.data(), buffer.size()); + if (bytes <= 0) + { + printf("%s", content.c_str()); + event.exit(bytes < 0); + return; + } + content.append(buffer.data(), bytes); + timer.restartOnce(delay); + }; + IO ioSource(event, STDIN_FILENO, EPOLLIN, std::move(ioCb)); + + return event.loop(); +} -- cgit v1.2.3