How to create timer events using C++ 11?
I need something like: “Call me after 1 second from now”.
Is there any library?
See Question&Answers more detail:osHow to create timer events using C++ 11?
I need something like: “Call me after 1 second from now”.
Is there any library?
See Question&Answers more detail:osMade a simple implementation of what I believe to be what you want to achieve. You can use the class later
with the following arguments:
You can change std::chrono::milliseconds
to std::chrono::nanoseconds
or microseconds
for even higher precision and add a second int and a for loop to specify for how many times to run the code.
Here you go, enjoy:
#include <functional>
#include <chrono>
#include <future>
#include <cstdio>
class later
{
public:
template <class callable, class... arguments>
later(int after, bool async, callable&& f, arguments&&... args)
{
std::function<typename std::result_of<callable(arguments...)>::type()> task(std::bind(std::forward<callable>(f), std::forward<arguments>(args)...));
if (async)
{
std::thread([after, task]() {
std::this_thread::sleep_for(std::chrono::milliseconds(after));
task();
}).detach();
}
else
{
std::this_thread::sleep_for(std::chrono::milliseconds(after));
task();
}
}
};
void test1(void)
{
return;
}
void test2(int a)
{
printf("%i
", a);
return;
}
int main()
{
later later_test1(1000, false, &test1);
later later_test2(1000, false, &test2, 101);
return 0;
}
Outputs after two seconds:
101