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 RemoveTimer(int32_t timerId);
38     int32_t ResetTimer(int32_t timerId);
39     bool IsExist(int32_t timerId);
40     int32_t CalcNextDelay();
41     void ProcessTimers();
42 
43 private:
44     struct TimerItem {
45         int32_t id { 0 };
46         int32_t intervalMs { 0 };
47         int32_t repeatCount { 0 };
48         int32_t callbackCount { 0 };
49         int64_t nextCallTime { 0 };
50         std::function<void()> callback;
51     };
52 private:
53     int32_t TakeNextTimerId();
54     int32_t AddTimerInternal(int32_t intervalMs, int32_t repeatCount, std::function<void()> callback);
55     int32_t RemoveTimerInternal(int32_t timerId);
56     int32_t ResetTimerInternal(int32_t timerId);
57     bool IsExistInternal(int32_t timerId);
58     void InsertTimerInternal(std::unique_ptr<TimerItem>& timer);
59     int32_t CalcNextDelayInternal();
60     void ProcessTimersInternal();
61 
62 private:
63     std::list<std::unique_ptr<TimerItem>> timers_;
64     std::recursive_mutex timerMutex_;
65 };
66 
67 #define TimerMgr ::OHOS::DelayedSingleton<TimerManager>::GetInstance()
68 } // namespace MMI
69 } // namespace OHOS
70 #endif // TIMER_MANAGER_H