0

I want create timer in my program so that I can cause it to rerun every minute and I don't know how to do it in a C++ Application. In C# I could just create a timer but I'm struggling here now...

sleep(); is not an option because as far as I know it makes your program inactive for X seconds, I need my app to be active and working, calculating all the time. This is because my code is used to constantly input information into a MS Access table. I was able to create the necessary components of my code to connect and perform the insert/update to the table but this is just on of the many components to the code that I am creating. Please help me with this little (or big?) problem, I'm very new to C++ and learning ATM, but I am developing a fast learning curve. Thanks

Andriy Tylychko
  • 15,967
  • 6
  • 64
  • 112
LaDante Riley
  • 521
  • 4
  • 14
  • 26
  • Check this out. http://stackoverflow.com/questions/4855597/how-do-i-create-a-timer-do-something-every-x-seconds-minutes-hours – sealz Jul 12 '11 at 19:36
  • I think that there are timers built-in in winapi. –  Jul 12 '11 at 19:37

5 Answers5

1

Every platform provides api for creating a timer, which will give you a callback usually after timer expires. You can just search for the api available on your platform.

If you are using windows use setTimer function.

Alok Save
  • 202,538
  • 53
  • 430
  • 533
1

I suppose you work on Windows, since you mentioned C#. So take a look at SetTimer, and if it is a MFC app, then look at CWnd::SetTimer.

Marius Bancila
  • 16,053
  • 9
  • 49
  • 91
  • I know that, but if I was to bet on that alone it was Windows I would have put the money with no problem; moreover, if you read below you can see a reference to MS Access. that means Windows :) – Marius Bancila Jul 12 '11 at 21:45
0

If you're using C++ .NET, you can use the same Timer class(es) as C#, just use the C++ syntax (using gcnew instead of new, use the ^ for GC references).

Otherwise you could just have a loop:

while (should_keep_looping) {
  // do what you need to do

  // if necessary:
  sleep(1);
}
robbrit
  • 17,560
  • 4
  • 48
  • 68
0

See here: http://www.cplusplus.com/forum/beginner/317/

There is on built in "timer" in C++, and you are correct about the behavior of sleep(). The above thread describes a custom implementation.

BlackJack
  • 2,826
  • 1
  • 22
  • 25
0
  • if you have a window you can use its message queue, as suggested by Als and Marius in their answers
  • you can use some task dispatcher and some timer to register a callback, e.g. functionality provided by Boost.Asio and its deadline_timer (example)
  • you can check if timer expired between your tasks manually as proposed in BlackJack's link
  • or you can create separate thread and make it call your callback when time came. Pros: you can use sleep() there and you callback will be called in parallel with your main thread. Cons: worry about synchronization
Andriy Tylychko
  • 15,967
  • 6
  • 64
  • 112