7

是否有使用 STL 实现的 TimerCallback 库。我无法将 Boost 依赖项引入我的项目。

到期的定时器应该能够回调注册的函数。

4

1 回答 1

11

标准库中没有特定的计时器,但很容易实现:

#include <thread>

template <typename Duration, typename Function>
void timer(Duration const & d, Function const & f)
{
    std::thread([d,f](){
        std::this_thread::sleep_for(d);
        f();
    }).detach();
}

使用示例:

#include <chrono>
#include <iostream>

void hello() {std::cout << "Hello!\n";}

int main()
{
    timer(std::chrono::seconds(5), &hello);
    std::cout << "Launched\n";
    std::this_thread::sleep_for(std::chrono::seconds(10));
}

请注意,该函数是在另一个线程上调用的,因此请确保它访问的任何数据都得到适当的保护。

于 2012-08-01T17:09:30.510 回答