TimerCallback函数基于没有Boost的标准模板库

TimerCallback function based on Standard Template LIbrary without Boost

本文关键字:Boost 标准模板库 于没 函数 TimerCallback      更新时间:2023-10-16

是否存在使用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 << "Launchedn";
    std::this_thread::sleep_for(std::chrono::seconds(10));
}

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