यहां हम C++ का उपयोग करके टाइमर बनाने का तरीका देखेंगे। यहां हम later नामक एक क्लास बना रहे हैं। इस क्लास में निम्नलिखित गुण हैं।
- int (कोड चलाने तक प्रतीक्षा करने के लिए मिलीसेकंड)
- bool (यदि यह सच है, तो यह तुरंत लौटता है, और निर्दिष्ट समय के बाद दूसरे थ्रेड पर कोड चलाता है)
- वेरिएबल आर्गुमेंट्स (सटीक रूप से हम std::bind को फीड करना चाहते हैं)
हम precision बदलने के लिए chrono::milliseconds को nanoseconds या microseconds आदि में बदल सकते हैं।
उदाहरण कोड
#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);
return 0;
}
आउटपुट
$ g++ test.cpp -lpthread $ ./a.out result of test 2: 75 result of test 2: 101 $
पहला परिणाम 4 सेकंड के बाद। दूसरा परिणाम पहले वाले के 3 सेकंड बाद।