The simple way would be something like this
#include <chrono>
#include <thread>
int main()
{
size_t seconds = 0;
while(seconds < 60)
{
std::this_thread::sleep_for(std::chrono::seconds(1));
seconds += 1;
if( seconds % 3 == 0 )
func1();
if( seconds % 6 == 0 )
func 2();
}
}
The problem with this approach is that your
main()
loop stops all work for 1 second, so if there's other things you want to be doing as well, then you're blocked until the sleep_for finishes.
If you try this within a loop and measure duration, you've got a couple of problems. Firstly, you'll almost never have an exact number of seconds, so you'll have to find a way to make sure you only trigger once per interval, and secondly, unless you've got other processing going on that needs to be done, then you're spending a lot of CPU time doing an "idle loop", which would drag down your system performace, and is probably something that you want to avoid.
Another, more advanced solution would be to put each function into its own thread with their own timing loop. That's tricky though: since each thread is triggering its own event, the order of execution will be undetermined, which may or may not be an issue. You will also have the problem of any shared resources (e.g. files, screen I/O, data blocks), which will need to be managed so that any changes get made in a sane manner. You will also need to be able to signal to your child threads to shutdown and clean up when the main thread ends.