是否有使用 STL 实现的 TimerCallback 库。我无法将 Boost 依赖项引入我的项目。
定时器到期时应该能够回调注册的函数。
最佳答案
标准库中没有特定的计时器,但很容易实现一个:
#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));
}
请注意该函数是在另一个线程上调用的,因此请确保它访问的任何数据都受到适当保护。
关于c++ - 基于没有 Boost 的标准模板库的 TimerCallback 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11763786/