如何在c++中使用boost实现与系统时间无关的计时器回调

How to implement timer callback independent of the system time in C++ using boost

本文关键字:时间 系统 回调 计时器 实现 c++ boost      更新时间:2023-10-16

我需要创建一个计时器,它将定期调用我的函数(例如每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一起使用可以得到正确的结果。

最后一种可能是只使用usleepnanosleep

但是要注意,你将不能用最后两个选项(STL和OS特定的调用)来中断睡眠。