need to call a function at periodic time intervals in c++

前端 未结 8 1121
悲&欢浪女
悲&欢浪女 2020-11-30 08:58

I am writing a program in c++ where I need to call a function at periodic time intervals, say every 10ms or so. I\'ve never done anything related to time or clocks in c++, i

8条回答
  •  悲&欢浪女
    2020-11-30 09:36

    To complete the question, the code from @user534498 can be easily adapted to have the periodic tick interval. It's just needed to determinate the next start time point at the beginning of the timer thread loop and sleep_until that time point after executing the function.

    #include 
    #include 
    #include 
    #include 
    
    void timer_start(std::function func, unsigned int interval)
    {
      std::thread([func, interval]()
      { 
        while (true)
        { 
          auto x = std::chrono::steady_clock::now() + std::chrono::milliseconds(interval);
          func();
          std::this_thread::sleep_until(x);
        }
      }).detach();
    }
    
    void do_something()
    {
      std::cout << "I am doing something" << std::endl;
    }
    
    int main()
    {
      timer_start(do_something, 1000);
      while (true)
        ;
    }
    

提交回复
热议问题