Here we will see how to make timer using C++. Here we are creating one class called later. This class has following properties.
- int (milliseconds to wait until to run code)
- bool (If this is true, it returns instantly, and run the code after specified time on another thread)
- The variable arguments (exactly we want to feed to std::bind)
We can change the chrono::milliseconds to nanoseconds or microseconds etc. to change the precision.
Example Code
#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("result of test 2: %d\n", a);
return;
}
int main() {
later later_test1(3000, false, &test1);
later later_test2(1000, false, &test2, 75);
later later_test3(3000, false, &test2, 101);
}Output
$ g++ test.cpp -lpthread $ ./a.out result of test 2: 75 result of test 2: 101 $
first result after 4 seconds. The second result after three seconds from the first one