Timers in C++? =x

SineCosine

I'm still looking for my Tangent
Reaction score
77
I'm sure there's a timer function..
Like..
Wait for 5seconds, then call a function.

I don't think it'd be nice to have the whole program freeze up while waiting, though.
So I don't want the timer to freeze the app.

How would I go about starting a timer?
 

Slapshot136

Divide et impera
Reaction score
471
you would need to make a 2nd thread that does whatever you want in 5 seconds, while your first thread keeps the application alive
 

GetTriggerUnit-

DogEntrepreneur
Reaction score
129
The function should not have params.
Code:
void setTimeout(long millis, void* targ)
{
    // new thread
    Sleep(millis);
    targ();
    // delete targ
}
 

Vestras

Retired
Reaction score
248
The function should not have params.
Code:
void setTimeout(long millis, void* targ)
{
    // new thread
    Sleep(millis);
    targ();
    // delete targ
}

Pretty sure you have to include Windows.h in order to have the sleep function. And "So I don't want the timer to freeze the app." then you should use multi threads. I realize you can't use it in C++, but you should look at MSDN for BackgroundWorker. It does what you need, but it's for .NET. But you can get some inspiration ;)
 

profet

New Member
Reaction score
7
You can also do this without multithreading at all, it would even be better since this solution drags a lot of complexity and performance issues.

You might know that a program is based on an "infinite" while-loop (called main-loop) generally placed in the main function (hence the name).
This while loops as fast as it can and updates the program each time.

So, if you want to call a function every 5seconds, you could increase a variable in the loop by the time elapsed since the last iteration. When the variable exceeds 5s, remove 5s from the variable and execute your function...
Thus, you can control the timing without interrupting the program execution.

That's the general concept, but many API provides easy ways to do that, like QTimer in Qt.
 
General chit-chat
Help Users
  • No one is chatting at the moment.

      The Helper Discord

      Members online

      No members online now.

      Affiliates

      Hive Workshop NUON Dome World Editor Tutorials

      Network Sponsors

      Apex Steel Pipe - Buys and sells Steel Pipe.
      Top