简体   繁体   中英

How do I create a timer run my program repeatedly? C++

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

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.

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 .

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);
}

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.

  • 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, eg 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM