简体   繁体   English

如何在C / C ++中实现计时器

[英]how to implement timer in C/C++

I want to call a function of the business class after every 2 hours. 我想每隔2小时调用一次商务舱的功能。 I m not getting any way to implement same in C/C++ without using a while loop. 我没有任何方法在不使用while循环的情况下在C / C ++中实现相同的功能。 My problem is that i cannot use while(1) as this does not retun back the control for further execution. 我的问题是我不能使用while(1),因为这不会重新调回控件以进一步执行。

Any pointer in this regards wud be helpful....:) 在这方面的任何指针都是有用的.... :)

thnaks thnaks

For a general solution, you could start a thread, which sends some message to the main thread after 2 hours. 对于一般解决方案,您可以启动一个线程,该线程在2小时后向主线程发送一些消息。

For linux, you could use this: 对于linux,你可以使用这个:

http://linux.die.net/man/3/alarm http://linux.die.net/man/3/alarm

and then handle the SIGALRM signal 然后处理SIGALRM信号

In plain C, I would've considered using the alarm(2) or setitimer(2) functions. 在简单的C中,我会考虑使用alarm(2)setitimer(2)函数。 Alternatively, spawn a thread and do the waiting from there. 或者,生成一个线程并从那里做等待。

If you decide on the alarm or setitimer routes, bear in mind that you'll need to write signal handlers and may need a dispatch loop to note that it is time to do the periodic maintenance calls, as it's considered bad practise to do quite a few things from within a signal handler. 如果您决定使用警报或设置路由,请记住您需要编写信号处理程序,并且可能需要一个调度循环来指示是时候进行定期维护调用,因为这样做被认为是不好的做法。信号处理程序中的一些东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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