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 CPPTIMER_H 17 #define CPPTIMER_H 18 19 #include <algorithm> 20 #include <chrono> 21 #include <functional> 22 #include <list> 23 #include <thread> 24 25 #include "CallbackQueue.h" 26 #include "PreviewerEngineLog.h" 27 28 class CppTimer { 29 public: 30 CppTimer() = delete; 31 CppTimer& operator=(const CppTimer&) = delete; 32 CppTimer(const CppTimer&) = delete; 33 34 ~CppTimer(); 35 36 // Use callback functions and parameters to construct a timer. the timer is repeatedly executed by default. 37 template <class Function, class... Args> CppTimer(Function callback,Args...args)38 explicit CppTimer(Function callback, Args... args) : interval(0), shotTimes(-1), isRunning(false) 39 { 40 functional = [callback, args...]() { return callback(args...); }; 41 threadId = std::this_thread::get_id(); 42 InitClock(); 43 } 44 45 // Use callback functions, parameters, and execution times to construct a timer. 46 template <class Function, class... Args> CppTimer(Function callback,Args...args,int shotTimes)47 CppTimer(Function callback, Args... args, int shotTimes) : interval(0), shotTimes(-1), isRunning(false) 48 { 49 functional = [callback, args...]() { return callback(args...); }; 50 this->shotTimes = shotTimes; 51 threadId = std::this_thread::get_id(); 52 InitClock(); 53 } 54 SetShotTimes(int timers)55 inline void SetShotTimes(int timers) 56 { 57 shotTimes = timers; 58 } 59 GetShotTimes()60 inline int GetShotTimes() const 61 { 62 return shotTimes; 63 } 64 IsRunning()65 inline bool IsRunning() const 66 { 67 return isRunning; 68 } 69 70 void Start(int64_t value); 71 72 void Stop(); 73 74 void RunTimerTick(CallbackQueue& queue); 75 76 private: 77 int64_t interval; 78 int32_t shotTimes; 79 std::thread::id threadId; 80 bool isRunning; 81 std::function<void()> functional; 82 std::chrono::system_clock::time_point startTime; 83 InitClock()84 void InitClock() 85 { 86 startTime = std::chrono::system_clock::now(); 87 } 88 }; 89 90 #endif // CPPTIMER_H 91