Time

Scheduler

It runs on even intervals between execution. Like the main loop in game engines - no matter how long it takes to process all components in the hiaerarchy in a single moment in time, the next moment will happen exactly after the scheduled delay.

Main loop

And this is useless for now but precise worker that repeats tasks at moments separated by the delay, skipping time required to execute tasks. So no matter how long tasks will take (if it less then the delay), the starting moment for tasks is exact

  void main_loop() {
    bool running = true;
    TimePoint prev_now = Clock::now();
    uint64_t step = 0;
    using std::chrono::operator""ms;
    auto step_delay = 1000ms;

    while (running) {
      TimePoint now = Clock::now();
      auto drift = std::chrono::duration_cast<Duration>(
              now - prev_now - step_delay).count();
      std::cout << "-- drift "  << drift << "ms " << std::endl;
      prev_now = now;

      run_tasks();

      TimePoint after_tasks = Clock::now();
      auto task_time = std::chrono::duration_cast<Duration>(
              after_tasks - now).count();
      std::cout << "-- task time "  << task_time << "ms " << std::endl;
      
      ++step;

      auto expected_time = now + step_delay;
      std::this_thread::sleep_until(expected_time);
    }
  }