Skip to content

How does one compose Streams with EventLoop Timers? #540

@mthiffau

Description

@mthiffau

I'd like to create a Stream which produces "ticks" at even time intervals. My current solution can do this by blocking the the thread which is producing the ticks with sleep calls, but obviously it would be more optimal if I could make use of a Timer.

The following doesn't work (I think because the bare 'Then' doesn't handle the Stream stuff?). Is there something similar I could do? Or would an entirely different approach be better?

class ClockActor : public StaticThreadPool::Schedulable {
  using clock = std::chrono::steady_clock;
  using milliseconds = std::chrono::milliseconds;
  using time_point = std::chrono::time_point<clock>;

public:
  ClockActor(Pinned pinned, milliseconds tick_period) :
    StaticThreadPool::Schedulable(pinned), tick_period_(tick_period) {}

  auto Ticks() {
    return Repeat()
      >> Until([this] () {
        return Schedule(Then([this] () {
          return count_ > 5; // This is just here while testing.
        }));
      })
      >> Schedule(Map([this] () mutable {
        time_point now = clock::now();
        if (last_tick_ == time_point()) {
          last_tick_ = now;
        }
        milliseconds time_since_last_tick =
          std::chrono::duration_cast<milliseconds>(now - last_tick_);
        milliseconds time_to_wait =
          std::chrono::duration_cast<milliseconds>(
            tick_period_ - (time_since_last_tick - tick_period_));
        printf("since last tick: %ld\n", time_since_last_tick.count());
        printf("time to wait: %ld\n", time_to_wait.count());
        return time_to_wait;
      }))
      >> Then([] (auto& wait_time) {
        return Timer(milliseconds(wait_time));
      })
      >> Schedule(Map([this] () mutable {
        last_tick_ = clock::now();
        return count_++;
      }));
  }

private:
  int count_ = 0;
  const milliseconds tick_period_;
  time_point last_tick_;
};

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions