How to call a function every n seconds in C++

In this tutorial, we are going to learn how to call a function every n seconds in C++. We are going to do this using two methods. One is using Sleep() function and other is using time() function. Let’s understand these methods in detail.

Call a function every n seconds in C++

We can call a function every n seconds in C++ by following these methods…

  • Using Sleep()
  • Using time()

Let’s discuss them separately.

Using Sleep()

We can use Sleep() function to make the program wait for some time and then execute. To use this function, we must include ‘Windows.h’ header in our program. This function takes arguments in milliseconds. Therefore, if we want our program to wait for 2 seconds before calling a function, we should pass 2000 in Sleep() function. See the program for a better understanding.

Special Note: Here we are using Windows.h header file so this code should work on only Windows OS. If you are using something else like Linux or mac just go for the second method which is time(). (Scroll down to see)

#include <iostream>
#include <Windows.h>
void fun();

using namespace std;

int main()
{
  int n;
  cout<<"Enter value of n."<<endl;
  cin>>n;
  int milli_seconds=n*1000;
  while(1)
  {
      fun();
      Sleep(milli_seconds);
  }
  
  
  return 0;
}
void fun()
{
  cout<<"Function"<< endl;
}

 

Output:

Enter value of n.
2
Function
Function
Function
........

As you can see, we have defined a function fun() which prints function on a line in each call. We are calling this function and then calling the sleep() function with argument n*1000 milliseconds. The program is halted for n seconds and then repeats the whole process again as we are passing 1 in the while loop.

Using time()

We can also do the above by using the time() function. As we know, when we call time() function with argument 0 or NULL, it returns total number of seconds. We can compare the values returned by time() function in two different calls and if it is n seconds, we call the function fun(), which prints function on the console screen.

See the code below.

#include <iostream>
#include <time.h>
void function();

using namespace std;

int main()
{
  int n;
  cout<<"Enter value of n."<<endl;
  cin>>n;
  int milli_seconds=n*1000;
  time_t start, end;
  start=time(0);
  while(1)
  {
    
    if(time(0)-start==n)
    {
      function();
      start=start+n;
    }
  }
  
  
  return 0;
}
void function()
{
  cout<<"Function"<< endl;
}

Output:

Enter value of n.
2
Function
Function
Function
........

In the above program, we first store the total seconds in the start variable. Then we call the time() function again with argument ‘0’ and compare it to value stored in the start variable. If it is equal to n then we call the function fun().

Thank you.

Also, read: Create a Digital Clock in C++

Leave a Reply

Your email address will not be published. Required fields are marked *