Well, of course, the advice to spawn off a separate thread (that's what I would do) or use alarm()
given in the comments is good advice, but may not be possible on your device. However, focusing on your current approach, generally the idea is, pseudo-code:
last action time = current time
while (true) {
do things.
if current time - last action time >= 5 minutes then
perform action
last action time = current time
// or last action time += 5 minutes if you want to mitigate drift
end
}
So now you just need to pick your favorite way to get the current time. On a desktop platform you could use e.g. time()
, gettimeofday()
, GetTickCount()
on Windows, etc. Some embedded platforms may provide those as well. However, this could be problematic:
Since you mentioned in a comment that you are working on an embedded device, "your favorite way to get the current time" will vary depending on the platform, you'll just have to check the device docs. If you're lucky, your MCU may provide a way to query the CPU counter, and the frequency you usually know already from your setup. But it may not.
If it does not, another alternative is if your device provides an on-board timer. In this case, you may be able to configure it and respond to periodic interrupts, in that case your two options are generally:
- Do the action in the timer interrupt handler - but only do this if it's short, and you take proper precautions for interrupt-safety.
- Set a
volatile
flag in the timer interrupt handler, check that flag in the main loop and execute the action + reset the flag there if it is set. This is generally a much simpler approach.
Doing it that way is architecturally similar to using alarm()
. However, there are certainly embedded platforms that implement time()
and/or gettimeofday()
as well. But those are your choices.