1 /* 2 * Copyright (c) 2021-2022 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 TIMER_MANAGER_H 17 #define TIMER_MANAGER_H 18 19 #include <functional> 20 #include <list> 21 #include <memory> 22 23 #include "singleton.h" 24 25 #include "define_multimodal.h" 26 #include "mmi_log.h" 27 #include "util.h" 28 29 namespace OHOS { 30 namespace MMI { 31 class TimerManager final { 32 DECLARE_DELAYED_SINGLETON(TimerManager); 33 34 public: 35 DISALLOW_COPY_AND_MOVE(TimerManager); 36 int32_t AddTimer(int32_t intervalMs, int32_t repeatCount, std::function<void()> callback); 37 int32_t AddLongTimer(int32_t intervalMs, int32_t repeatCount, std::function<void()> callback); 38 int32_t RemoveTimer(int32_t timerId); 39 int32_t ResetTimer(int32_t timerId); 40 bool IsExist(int32_t timerId); 41 int32_t CalcNextDelay(); 42 void ProcessTimers(); 43 44 private: 45 struct TimerItem { 46 int32_t id { 0 }; 47 int32_t intervalMs { 0 }; 48 int32_t repeatCount { 0 }; 49 int32_t callbackCount { 0 }; 50 int64_t nextCallTime { 0 }; 51 std::function<void()> callback; 52 }; 53 private: 54 int32_t TakeNextTimerId(); 55 int32_t AddTimerInternal(int32_t intervalMs, int32_t repeatCount, std::function<void()> callback); 56 int32_t RemoveTimerInternal(int32_t timerId); 57 int32_t ResetTimerInternal(int32_t timerId); 58 bool IsExistInternal(int32_t timerId); 59 void InsertTimerInternal(std::unique_ptr<TimerItem>& timer); 60 int32_t CalcNextDelayInternal(); 61 void ProcessTimersInternal(); 62 63 private: 64 std::list<std::unique_ptr<TimerItem>> timers_; 65 std::recursive_mutex timerMutex_; 66 }; 67 68 #define TimerMgr ::OHOS::DelayedSingleton<TimerManager>::GetInstance() 69 } // namespace MMI 70 } // namespace OHOS 71 #endif // TIMER_MANAGER_H