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