Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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++, is this a quick and easy problem or one of those where there is no neat solution?

Thanks!

like image 832
Execut1ve Avatar asked Jan 11 '14 02:01

Execut1ve


3 Answers

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 <iostream>
#include <chrono>
#include <thread>
#include <functional>

void timer_start(std::function<void(void)> 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)
    ;
}
like image 83
florgeng Avatar answered Oct 01 '22 06:10

florgeng


A simple timer can be implemented as follows,

#include <iostream>
#include <chrono>
#include <thread>
#include <functional>

void timer_start(std::function<void(void)> func, unsigned int interval)
{
    std::thread([func, interval]() {
        while (true)
        {
            func();
            std::this_thread::sleep_for(std::chrono::milliseconds(interval));
        }
    }).detach();
}


void do_something()
{
    std::cout << "I am doing something" << std::endl;
}

int main() {
    timer_start(do_something, 1000);

    while(true);
}

This simple solution does not offer a way to stop the timer. The timer will keep running until the program exited.

like image 24
user534498 Avatar answered Oct 01 '22 07:10

user534498


If you're coding with Visual C++, you could add a timer element to the form you want to call a periodic function (here it's called my form is MainForm, and my timer MainTimer). Add a call to the tick event in the "Events". The designer will add such line in your .h file:

this->MainTimer->Enabled = true;
this->MainTimer->Interval = 10;
this->MainTimer->Tick += gcnew System::EventHandler(this, &MainForm::MainTimer_Tick);

Then, at each interval (specified in ms), the application will call this function

private: System::Void MainTimer_Tick(System::Object^  sender, System::EventArgs^  e) {
   /// Enter your periodic code there
}
like image 40
RawBean Avatar answered Oct 01 '22 06:10

RawBean