A
A
Alexey2014-04-04 14:40:09
C++ / C#
Alexey, 2014-04-04 14:40:09

How to organize a timer in C?

I'm almost sure that the question is trite, but for some reason I can't find a good solution.
There is a program sitting in an infinite loop. Once a minute, this cycle must be interrupted and certain actions must be performed. Moreover, you need to interrupt it at the beginning of the minute, i.e. after the zero second. Time can be corrected by GPS, so you need to be tied to the beginning of the minute, and not to the time interval.
How can this be done correctly? The solutions I come across are based on polling the clock with the sleep/usleep function. But this loads the processor significantly, and the program should ideally sit and not take up processor time until the beginning of the minute comes.

Answer the question

In order to leave comments, you need to log in

5 answer(s)
X
xandox, 2014-04-04
@WildHorn

you can set sleep for a second and check every second whether the minute has started.
when the process is in sleep it does not use the processor at all, so it does not load anything.

R
Rsa97, 2014-04-04
@Rsa97

Adaptive sleep, say for half or three quarters of the interval remaining until zero second?

R
rosperitus, 2014-04-04
@rosperitus

If you are writing under Windows, then here is the timeSetEvent function

L
leclecovich, 2014-04-04
@leclecovich

linux.die.net/man/2/gettimeofday

L
leclecovich, 2014-04-05
@leclecovich

An infinite loop with sleep is not a very elegant solution. If nothing prevents you from switching to C ++, then build boost and use asio. Here is an example www.boost.org/doc/libs/1_49_0/doc/html/boost_asio/... adapt it to your needs. Also look at boost::posix_time::time_period.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question