1 /* 2 * Copyright (c) 2023 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16 #ifndef NATIVE_XCOMPONENT_TIMER_H 17 #define NATIVE_XCOMPONENT_TIMER_H 18 19 #include <iostream> 20 #include <chrono> 21 #include <thread> 22 #include <future> 23 #include <atomic> 24 #include <functional> 25 26 class Timer { 27 public: Timer()28 Timer() : is_running(false) 29 {} 30 start(std::chrono::milliseconds total_duration,std::chrono::milliseconds interval,std::function<void ()> task)31 void start(std::chrono::milliseconds total_duration, std::chrono::milliseconds interval, std::function<void()> task) 32 { 33 stop(); // 确保之前的计时器停止 34 is_running = true; 35 timer_future = std::async(std::launch::async, [=]() { 36 auto start_time = std::chrono::steady_clock::now(); 37 auto end_time = start_time + total_duration; 38 auto next_check = start_time; 39 40 while (is_running.load() && std::chrono::steady_clock::now() < end_time) { 41 std::this_thread::sleep_until(next_check); 42 next_check += interval; 43 if (is_running.load()) { 44 task(); 45 } 46 } 47 is_running = false; // 确保在结束时将 is_running 设置为 false 48 }); 49 } 50 stop()51 void stop() 52 { 53 is_running = false; 54 if (timer_future.valid()) { 55 timer_future.wait(); 56 } 57 } 58 ~Timer()59 ~Timer() 60 { 61 stop(); 62 } 63 64 private: 65 std::atomic<bool> is_running; 66 std::future<void> timer_future; 67 }; 68 69 #endif // NATIVE_XCOMPONENT_TIMER_H 70