Skip to content

Commit

Permalink
Add timer::set_interval
Browse files Browse the repository at this point in the history
  • Loading branch information
tekezo committed Oct 18, 2023
1 parent 662a3ec commit 770cb3e
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 5 deletions.
17 changes: 17 additions & 0 deletions include/pqrs/dispatcher/extra/timer.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -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);
Expand Down
43 changes: 38 additions & 5 deletions tests/src/timer_test.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -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();
}
Expand All @@ -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:
Expand Down Expand Up @@ -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<pqrs::dispatcher::hardware_time_source>();

{
size_t count = 0;

auto d = std::make_shared<pqrs::dispatcher::dispatcher>(time_source);

std::shared_ptr<timer_test> t;

t = std::make_shared<timer_test>(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();
}
};
}

0 comments on commit 770cb3e

Please sign in to comment.