好吧,如果我的应用程序正在运行,我需要弄清楚如何在特定时间调用函数.
它可能会在一个while循环中检查时间,但我不希望它每分钟检查一次,但我不希望它错过确切的时间,比如18:00.
这有什么办法吗?
如果要从已经运行的程序中调用特定函数,请使用Boost的日期时间库和Asio.
#include <boost/date_time/gregorian/gregorian_types.hpp>
#include <boost/date_time/posix_time/posix_time_types.hpp>
#include <boost/asio.hpp>
namespace gregorian = boost::gregorian;
namespace posix_time = boost::posix_time;
namespace asio = boost::asio;
asio::io_service io_service_;
asio::deadline_timer timer_ (io_service_);
Run Code Online (Sandbox Code Playgroud)
然后设置时间.这是使用所需时间的字符串的示例,例如"18:00:00".(请注意,Boost默认为UTC时间戳!)
gregorian::date today = gregorian::day_clock::local_day();
posix_time::time_duration usertime = posix_time::duration_from_string(time)
posix_time::ptime expirationtime (today, usertime);
Run Code Online (Sandbox Code Playgroud)
现在设置要调用的计时器foo():
timer_.expires_at (expirationtime);
timer_.async_wait (foo); // use Boost::bind() if you want a member function
Run Code Online (Sandbox Code Playgroud)
您可以timer_使用上述两个代码段添加任意数量的计时器.一切准备就绪:
io_service_.run ();
Run Code Online (Sandbox Code Playgroud)
请注意,这将接管当前线程.因此,run()如果您希望程序的其余部分继续运行,则必须从另一个线程调用.(显然,使用Boost的Thread库.)
| 归档时间: |
|
| 查看次数: |
4976 次 |
| 最近记录: |