TimerCallback function based on the standard LIbrary template without Boost

Are TimerCallback libraries implemented using STL? I cannot cast Boost dependency in my project.

Upon expiration, the timer must be able to call back the registered function.

+5
source share
1 answer

There is no specific timer in the standard library, but it is quite simple to implement it:

#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();
}

Usage example:

#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));
}

Beware that the function is called in another thread, so make sure that any data it accesses is protected.

+8
source

All Articles