如何在 c++ 中每天的某个时间调用一个函数?
好吧,我需要弄清楚如果我的应用程序正在运行,如何在某个时间调用函数。
它可能会在一个 while 循环中检查时间,但我不希望它每分钟检查一次时间,但我不希望它错过确切的时间,比如 18:00。
有什么办法吗?
Well i need to figure out how to call a function at a certain time if my application is running.
it will probably be in a while loop and check the time but i don't want it to check the time every minute but i don't want it to miss the exact time, say 18:00.
is there any way do to this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您想从已运行的程序中调用特定函数,请使用 Boost 的 日期时间库和Asio。
然后设定时间。这是使用所需时间字符串的示例,例如“18:00:00”。 (请注意,Boost 默认使用 UTC 作为时间戳!)
现在设置计时器来调用
foo()
:您可以使用以下命令向
timer_
添加任意数量的计时器:上面两个代码片段。当一切准备就绪时:请注意,这将接管当前线程。因此,如果您希望程序的其余部分继续运行,则必须从不同的线程调用
run()
。 (显然,请使用 Boost 的 Thread 库。)If you want to call a specific function from within a program that's already running, use Boost's Date Time library and Asio.
Then set the time. This is an example using a string of the desired time, like "18:00:00". (Note that Boost defaults to UTC for the timestamps!)
Now set the timer to call
foo()
:You can add as many timers as you want to
timer_
by using the above two code snippets. When everything is ready:Note that this will take over the current thread. So you must call
run()
from a different thread if you want the rest of your program to keep going. (Obviously, use Boost's Thread library for that.)编辑:我不知道为什么我认为这是Windows。我没有看到任何地方有这样的说法。以下API信息仅适用于Windows,但原理是相同的。 Boost.Asio 有便携式异步计时器(如果不是 Windows)。
Windows 信息:当您的应用启动时,检查所需事件的剩余时间间隔并启动 定时器队列定时器在适当的时间弹出。计时器将在初始间隔后弹出,然后在定期间隔后重复弹出。
使这种事件驱动比定期检查时钟更有效。
EDIT: I don't know why I assumed this was Windows. I don't see anywhere that it says so. The API info below is only applicable for Windows but the principle is the same. Boost.Asio has portable async timers, if not Windows.
Windows Info : When your app starts up, check the interval remaining to your desired event and start a Timer Queue Timer to pop at the appropriate time. The timer will pop after an initial interval, and then repeatedly after a periodic interval.
Much more efficient to make this event-driven than to periodically check the clock.
最好的方法是使用提供此功能的操作系统工具,而您只需担心编写函数即可。但如果这不是一个选择,您将需要按照您所说的定期检查时钟。
The best way would be to use the operating system tools that provide this and you only worry about writing your function. But if thats not an option you will need to just check the clock periodicly as you said.
您可以在系统中安装计划任务来通知您的应用程序。
例如,如果您的系统是 Linux,则可以使用 cron。
You could install a scheduled task in your system that will notify your application.
If your system is Linux you can use cron for example.