diff options
| author | William A. Kennington III <wak@google.com> | 2018-09-20 11:35:11 -0700 |
|---|---|---|
| committer | William A. Kennington III <wak@google.com> | 2018-09-26 12:18:50 -0700 |
| commit | ba04ffb5a94fd47d8acc57c7a6be4d31624d2c23 (patch) | |
| tree | aa8629e7418795879a563ff9dc6909985b79899e /example/delayed_echo.cpp | |
| parent | fa9431d52f37bf51a2aa0d3a85eaaf027db8488f (diff) | |
| download | sdeventplus-ba04ffb5a94fd47d8acc57c7a6be4d31624d2c23.tar.gz sdeventplus-ba04ffb5a94fd47d8acc57c7a6be4d31624d2c23.zip | |
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 <wak@google.com>
Diffstat (limited to 'example/delayed_echo.cpp')
| -rw-r--r-- | example/delayed_echo.cpp | 59 |
1 files changed, 59 insertions, 0 deletions
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 <array> +#include <chrono> +#include <cstdio> +#include <sdeventplus/clock.hpp> +#include <sdeventplus/event.hpp> +#include <sdeventplus/source/io.hpp> +#include <sdeventplus/utility/timer.hpp> +#include <string> +#include <unistd.h> +#include <utility> + +using sdeventplus::Clock; +using sdeventplus::ClockId; +using sdeventplus::Event; +using sdeventplus::source::IO; + +constexpr auto clockId = ClockId::RealTime; +using Timer = sdeventplus::utility::Timer<clockId>; + +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<char, 4096> 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(); +} |

