Calling a function for each second

In my program I want to call a function for each second. Once the function has been called it should be called again after an exact second. Like this I want to call the function for each second.
How can this be done? I tried with the function clock() in <ctime> as well. It didn't work since it didn't allow me to measure the time duration of a second in an accurate manner.
Please help me on this.

Thanks in Advance!
Last edited on
1. modern compiler option: spawn a thread that runs an endless loop that sleeps for one second and calls your function

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <thread>
#include <chrono>
void fn()
{
    for(;;)
   {
        std::this_thread::sleep_for(std::chrono::seconds(1));
        // <-- call your function here
   }
}
int main()
{
    std::thread(fn).detach();
    // <- do something that takes more than a second here
}


2. any compiler option: start a boost.asio timer with a callback that is your function: here's a tutorial http://www.boost.org/doc/libs/1_49_0/doc/html/boost_asio/tutorial/tuttimer2.html

3. for completeness: use system-specific timer API (e.g. setitimer() on POSIX) and write a signal handler (e.g. SIGALRM on POSIX) that calls your function.

Note that all options have varying degrees of precision, and nothing gives the absolute "exact second".
Last edited on
If you don't have c++11:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <ctime>

using namespace std;

int main()
{
     int a=clock()/CLOCKS_PER_SEC;//this gets the time in sec.
     while(true)
     {
           while(clock()/CLOCKS_PER_SEC-a<1);
           //call your function
           a=clock()/CLOCKS_PER_SEC;
           }
     }
Topic archived. No new replies allowed.