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 TIMER_MANAGER_H
17 #define TIMER_MANAGER_H
18 
19 #include <cinttypes>
20 #include <functional>
21 #include <list>
22 #include <memory>
23 #include <mutex>
24 #include <thread>
25 
26 #include "singleton.h"
27 #include "util.h"
28 
29 namespace OHOS {
30 namespace Rosen {
31 
32 enum class TimerMgrState {
33     STATE_NOT_START,
34     STATE_RUNNING,
35     STATE_EXIT
36 };
37 class TimerManager final {
38     DECLARE_DELAYED_SINGLETON(TimerManager);
39 
40 public:
41     DISALLOW_COPY_AND_MOVE(TimerManager);
42     void Init();
43     int32_t AddTimer(int32_t intervalMs, std::function<void()> callback);
44     int32_t RemoveTimer(int32_t timerId);
45 private:
46     struct TimerItem {
47         int32_t id { 0 };
48         int32_t intervalMs  { 0 };
49         int64_t nextCallTime  { 0 };
50         std::function<void()> callback;
51     };
52 private:
53     void OnThread();
54     void OnStop();
55     int32_t CalcNextDelay();
56     void ProcessTimers();
57     int32_t TakeNextTimerId();
58     int32_t AddTimerInternal(int32_t intervalMs, std::function<void()> callback);
59     int32_t RemoveTimerInternal(int32_t timerId);
60     void InsertTimerInternal(std::unique_ptr<TimerItem>& timer);
61     int32_t CalcNextDelayInternal();
62     void ProcessTimersInternal();
63 
64 private:
65     std::recursive_mutex mutex_;
66     std::atomic<TimerMgrState> state_ { TimerMgrState::STATE_NOT_START };
67     std::thread timerWorker_;
68     std::list<std::unique_ptr<TimerItem>> timers_;
69 };
70 } // namespace Rosen
71 } // namespace OHOS
72 #endif // TIMER_MANAGER_H