Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TimerCallback function based on Standard Template LIbrary without Boost

Tags:

c++

stl

timer

Are there TimerCallback libraries implemented using STL. I can't bring in Boost dependency into my project.

The timer on expiry should be able to callback the registered function.

like image 690
ssk Avatar asked Aug 01 '12 16:08

ssk


1 Answers

There's no specific timer in the standard library, but it's easy enough to implement one:

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

Example of use:

#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 invoked on another thread, so make sure any data it accesses is suitably guarded.

like image 126
Mike Seymour Avatar answered Sep 24 '22 03:09

Mike Seymour