如何在c++中使用boost实现与系统时间无关的计时器回调
How to implement timer callback independent of the system time in C++ using boost
我需要创建一个计时器,它将定期调用我的函数(例如每50毫秒)。但问题是,我需要改变系统时间,而计时器正在运行。我想这样做,使用boost,使代码是可移植的。否则我在Linux机器上运行。
我尝试过的事情:
- 尝试使用while循环和thread::sleep。使用steady_clock计算睡眠时间。
- 也尝试使用deadline_timer
当系统时间被调整时,这两个都停止工作。
问题:是否有任何方法(最好使用boost)来创建一个独立于系统时间的回调计时器?
似乎是linux下的一个bug。您需要使用睡眠方法,使用CLOCK_MONOTONIC
(boost::this_thread::sleep
使用CLOCK_REALTIME
)。带有boost时钟库的boost::this_thread::sleep_for
应该这样做,因为它使用单调时钟。
while (true) {
// Call your function here.
boost::this_thread::sleep_for(boost::chrono::milliseconds(100));
}
或者您可以使用boost::this_thread::sleep_until
。使用该函数,您可以使用自定义时钟。
基础CLOCK_MONOTONIC
可受adjtime()
的影响。因此,您可以使用CLOCK_MONOTONIC_RAW
作为linux的唯一选择。
还有一种可能性:如果你能使用c++ 11,你可以使用std::chrono::steady_clock
来获得一个严格的单调时钟。
auto start = std::chrono::steady_clock::now();
while (true) {
std::cout << (start - std::chrono::steady_clock::now()).count() << std::endl;
}
如果系统时钟被调整,这里的输出将不会改变。但不要将此用于boost::this_thread
。与std::this_thread::sleep_for
一起使用可以得到正确的结果。
最后一种可能是只使用usleep
或nanosleep
。
但是要注意,你将不能用最后两个选项(STL和OS特定的调用)来中断睡眠。
相关文章:
- c++ 11 如何获取系统时间?
- 如何使用跨平台代码在C++中设置系统时间?
- 如何使用 CTIME/Chrono Libarey 将开始时间与系统时钟进行比较
- 将系统时间与变量进行比较 - C++
- 即使在多任务处理时,添加用户时间 + 系统时间(来自 shell 的时间命令)是否是一种可靠的措施?
- 系统时间从何而来?
- 对于同一任务,线程的等待时间在 0 到 30000 微秒之间系统地切换
- 测量 std::系统的实际执行时间(以 C++ 为单位)
- Qthread ::更改系统时间时睡眠不正常
- 如何在跨平台C++中以毫秒为单位获得系统启动/启动时间(它应该在Windows / IOS / Android / MA
- 查找系统调用需要多长时间的可能方法
- 在C++的主逻辑中接收真实/用户/系统时间
- 为什么在获取系统时间时在此处使用“atomic_signal_fence”
- 使用rdtsc计算系统时间
- 用C++设置windows系统时间
- 如何使用套接字编程获取系统日期和时间
- 最佳C 11测量嵌入式系统代码执行时间的方法
- 具有较低系统时间的C++时序方法
- 不取决于系统时间的时间
- 我如何在C 的毫秒内获得系统的时间