From 770cb3e7ce44142a4a3d6b00431d374885d92183 Mon Sep 17 00:00:00 2001 From: Takayama Fumihiko Date: Wed, 18 Oct 2023 23:20:06 +0900 Subject: [PATCH] Add timer::set_interval --- include/pqrs/dispatcher/extra/timer.hpp | 17 ++++++++++ tests/src/timer_test.hpp | 43 ++++++++++++++++++++++--- 2 files changed, 55 insertions(+), 5 deletions(-) diff --git a/include/pqrs/dispatcher/extra/timer.hpp b/include/pqrs/dispatcher/extra/timer.hpp index fcdd79e..655d1c7 100644 --- a/include/pqrs/dispatcher/extra/timer.hpp +++ b/include/pqrs/dispatcher/extra/timer.hpp @@ -62,6 +62,19 @@ class timer final { return enabled_; } + void set_interval(duration interval) { + if (interval == duration(0)) { + stop(); + } else { + dispatcher_client_.enqueue_to_dispatcher([this, interval] { + ++current_function_id_; + interval_ = interval; + + enqueue(current_function_id_); + }); + } + } + private: // This method is executed in the dispatcher thread. void call_function(int function_id) { @@ -79,6 +92,10 @@ class timer final { }); } + enqueue(function_id); + } + + void enqueue(int function_id) { dispatcher_client_.enqueue_to_dispatcher( [this, function_id] { call_function(function_id); diff --git a/tests/src/timer_test.hpp b/tests/src/timer_test.hpp index 2583670..c48e6cf 100644 --- a/tests/src/timer_test.hpp +++ b/tests/src/timer_test.hpp @@ -19,6 +19,13 @@ class timer_test final : public pqrs::dispatcher::extra::dispatcher_client { duration); } + virtual ~timer_test(void) { + timer_.stop(); + + detach_from_dispatcher([] { + }); + } + void stop(void) { timer_.stop(); } @@ -27,11 +34,8 @@ class timer_test final : public pqrs::dispatcher::extra::dispatcher_client { return timer_.enabled(); } - virtual ~timer_test(void) { - timer_.stop(); - - detach_from_dispatcher([] { - }); + void set_interval(pqrs::dispatcher::duration interval) { + timer_.set_interval(interval); } private: @@ -118,4 +122,33 @@ void run_timer_test(void) { d->terminate(); } }; + + "dispatcher.timer (set_interval)"_test = [] { + std::cout << "dispatcher.timer (set_intervald)" << std::endl; + + auto time_source = std::make_shared(); + + { + size_t count = 0; + + auto d = std::make_shared(time_source); + + std::shared_ptr t; + + t = std::make_shared(d, count, std::chrono::milliseconds(10000), [] {}); + + std::this_thread::sleep_for(std::chrono::milliseconds(500)); + + expect(count == 1_i); + + t->set_interval(std::chrono::milliseconds(100)); + + std::this_thread::sleep_for(std::chrono::milliseconds(500)); + + expect(count > 2); + expect(count < 8); + + d->terminate(); + } + }; }