Re: Is There a C++ Timer Like the java.util.Timer
On Thursday, July 11, 2013 10:15:22 PM UTC+1, Paavo Helde wrote:
Victor Bazarov <firstname.lastname@example.org> wrote in
Prior to C++11, the standard was silent on sleep-type functions.
To add, there is a whole bunch of timer/clock/chrono functions in
C++11 (see subclause 20.11 of the Standard), but none of them are
designed to make use of a callback, so you'd have to "roll your own"
if your OS API doesn't provide you with anything suitable.
For making a timer-based callback there must be some kind of event loop
which could receive the callback.
I implemented this functionality in an OS way back around 1980
(not in C++, of course), and there was no event loop. For that
matter, there is no event loop in Java, and they implement it.
In GUI programs such an event loop is (almost?) always
present, so it can be re-utilized easily. C++ however is
defined on a more general level and cannot assume presence of
a GUI or an event loop.
Nor can Java. What Java *can* count on is threads. According
to the documentation, each Timer object is a thread.
In C++11, a standard way to do this would indeed be to start a new timer
thread. The thread would sleep for or until the specified time between the
tasks. If there is an event loop present, the timer thread could send a
specific event to it. If there is no event loop, the timer thread could
perform the periodic task by itself. There are many possibilities how to
set such a thing up.
You seem to be fixed on event loops. According to the specs for
java.util.Timer, the action is executed in the timer thread.
(FWIW: I don't think it would take more than about 10-15 lines
of code to implement the equivalent in C++11.)