Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <thread>
- #include <chrono>
- // 定時器
- // ms : Callbake時間
- // callback : Signature bool(long long)
- // 當callback return true時,timer便會停止
- void timer(long long ms,std::function<bool(long long ms)> callback)
- {
- using namespace std::chrono;
- auto p = system_clock::now(); // 記録現在時間
- auto next = ms; // 下一次callback時間
- // busy loop
- while (true) {
- // 使用yield()以避免CPU資源佔用
- std::this_thread::yield();
- auto duration = system_clock::now() - p; // 持續時間
- auto millis = duration_cast<milliseconds>(duration).count(); // 轉致ms
- // 當持續時間 > 下一次callback時間
- if (millis >= next) {
- // post callback & if return true exit this times
- if (callback(millis)) break;
- next += ms; // 下一次callback時間
- }
- }
- }
- int main()
- {
- // 定時器:毎10ms回呼(Callback)一次
- timer(10, [](long long ms){
- std::cout << "time stamp: " << ms << " ms" << std::endl;
- return (ms >= 1000); // 如果比1000ms大的話,timer停止
- });
- system("pause");
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement