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!
A simple timer can be implemented as follows,
This simple solution does not offer a way to stop the timer. The timer will keep running until the program exited.
Sorry, but I didn't find a design simpler than that.
You could, make a class that owns both a thread, and a
weak_ptr
to itself, to be a "holder" that the callable can see it safely, because the callable will still exists even if the object is destructed. You don't want a dangling pointer.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 beginnig of the timer thread loop and
sleep_until
that time point after executing the function.It depends on what you would be doing on per interval - displaying time/ticker or something else at specific location of screen/form. Or you may need to send regular data to some connected machine (over socket or pipe). Do you really need 10 millisecond precision?
Depending on requirement, especially the precision requirement, you may have dedicated thread to do 'something', then wait and do same thing again. Or, on Windows, you may use
SetTimer
that would triggerWM_TIMER
event on each interval (it wouldn't require thread). You may also use waitable timer, multimedia timer etc.At last, but quite important - Do you need platform and compiler compatibility? Meaning that, which OS you would be using, or you need platform independent? What compiler features you are looking for (C++11, C++14 or pre C++11).
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 timerMainTimer
). Add a call to the tick event in the "Events". The designer will add such line in your .h file:Then, at each interval (specified in ms), the application will call this function
You could look into threading:
Here's a time interval controlled function implemented in C, using pthread.h, it should be a simple port to C++. Executing a function at specific intervals