How to set a timer

Hey, I am working on a project where I need to set a 5 min. timer. Once timer is up I need to do something. I am not sure how to do this, any help will be greatly appreciated.
closed account (28poGNh0)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# include <windows.h>
# include <iostream>
using namespace std;

void timer(int sec)
{
    Sleep(sec*1000);
}

int main()
{
    cout << "Wait 5 seconds " << endl;
    timer(5);
    cout << "FireWorks !" << endl;

    return 0;
}
Techno01,
Thanks for the reply, but is there a way to set a timer and processing continues. To my understanding when you use sleep(), all processing stops. Is there a why to use settimer() in a non-dialog program? Any advice will be greatly appreciated!!
You can just make 1 timer that sleeps every second , and a i=300;
and i-- every second, when i=0 then do what u want to do :P
Thanks. Can you give me an example of what you are describing, just to make I am following.
Thanks
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int i=min*60;
void timer()
{
Sleep(1000)
dowhatuwantinmeantime 
i--;
if(i>0)
{
timer();
}
else
{
functionthatuwanttouseproccess();
}
}
Last edited on
Thanks. What is time()?
xD timer() sry my mistake it calls it self
Ok. What does min start value.
u set the min, 5 minutes, 10 minutes , how u want
using windows sleep func makes your program for windows only so its better to use this one

1
2
3
4
5
6
7
8
9
// you need to include ctime
void sleep(int timer)
{
int stime=time();
while(true)
{
if (time()-stime==timer) break;
}
}


and for making things while the timer is working you should use multithreading (search for multithreading in c++11 tutorial or use boost library)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <chrono>
#include <thread>

int main()
{
  std::thread timer([]() {
    std::this_thread::sleep_for(std::chrono::minutes(5));
    std::cout << "hello, world!" << std::endl;
    //Or call to function, or whatever you want
  });
  std::cout << "thread begun..." << std::endl;
  //code to do while waiting here.
  timer.join(); //Before program finishes. Basically "Wait for thread end"
}
Topic archived. No new replies allowed.